查询 MongoDB 中的嵌套文档

Querying on nested document in MongoDB

我有一个复杂的文档结构,如下所示 -

{
    "Application": {
        "DEF": {
            "Year": {
                "2018": {
                    "Quarter": {
                        "Q1": {
                            "Microservice": [ "A", "B" ]
                        },
                        "Q2": {
                            "Microservice": [ "C", "D" ]
                        },
                        "Q3": {
                            "Microservice": [ "E" ]
                        },
                        "Q4": {
                            "Microservice": [ "F", "G" ]
                        }
                    }
                },
                "2019": {
                    "Quarter": {
                        "Q1": {
                            "Microservice": [ "A", "C" ]
                        },
                        "Q2": {
                            "Microservice": [ "D" ]
                        },
                        "Q3": {
                            "Microservice": [ "E", "F" ]
                        },
                        "Q4": {
                            "Microservice": [ "G" ]
                        }
                    }
                }
            }
        }
    },
    "Product Name": "XYZ"
}

我正在尝试查询应用程序为 DEF、年份为 2018 和所有季度的所有记录。我试过像下面这样的 DOT(.) 符号 --

db.productsTest.find({"Application.DEF.Year.2018": {$exists: true}})

以上 returns 所有年份(2018 年和 2019 年)的结果,而不是仅返回 2018 年的年份、季度和微服务组合。这也可能是因为 JSON 结构和我无法按年份过滤(因为它们是嵌套的)。基本上我正在寻找 returns 这个 --

的查询
{
    "Application": {
        "DEF": {
            "Year": {
                "2018": {
                    "Quarter": {
                        "Q1": {
                            "Microservice": [ "A", "B" ]
                        },
                        "Q2": {
                            "Microservice": [ "C", "D" ]
                        },
                        "Q3": {
                            "Microservice": [ "E" ]
                        },
                        "Q4": {
                            "Microservice": [ "F", "G" ]
                        }
                    }
                }
            }
        }
    },
    "Product Name": "XYZ"
}

考虑到我的 JSON 结构,这个结果甚至可能吗?

以下查询完成工作:

db.productsTest.find({
    "Application.DEF.Year.2018": { $exists: true } // exclude documents from the result that do not contain the subdocument that we are interested in
}, {
    "_id": 0, // we do not want the _id field in the result document
    "Product Name" : 1, // but the "Product Name" should be included
    "Application.DEF.Year.2018": 1 // and so should be the subdocument we are interested in
})

基本上,这只是一个标准 query with a projection

$exists is an element operator 检查 属性 是否存在。

您可以使用$exists运算符来查找包含指定字段的文档!使用您提供的测试数据这对我有用:

db.productsTest.findOne({"Application.DEF.Year.2018.Quarter.Q1":{$exists:true}})

和returns您提供的测试文档。

附带说明:除非您有充分的理由使用这种深度嵌套结构,否则扁平化文档有助于提高可读性。