MongoDB查询以仅获取嵌套数组文档中的特定字段?

要仅获取嵌套数组文档中的特定字段,请使用$filter和$project。让我们创建一个包含文档的集合-

> db.demo342.insertOne({
...    "Id": "101",
...       "details1" : {
...          "details2" : [
...             {
...                "details3" : [
...                   {
...                      "Name": "Mike",
...                      "CountryName" : "US"
...                   },
...                   {
...                      "Name": "David",
...                      "CountryName" : "AUS"
...                   },
...                   {
...                      "Name": "Bob",
...                      "CountryName" : "UK"
...                   }
...                ]
...             }
...          ]
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e53ef99f8647eb59e5620a9")
}

find()方法的帮助下显示集合中的所有文档-

> db.demo342.find();

这将产生以下输出-

{ "_id" : ObjectId("5e53ef99f8647eb59e5620a9"), "Id" : "101", "details1" : { "details2" : [ { "details3" : [ { "Name" : "Mike", "CountryName" : "US" }, { "Name" : "David", "CountryName" : "AUS" }, { "Name" : "Bob", "CountryName" : "UK" } ] } ] } }

以下是仅获取嵌套数组文档中特定字段的查询-

> db.demo342.aggregate([
...    { "$project": {
...       "details1": {
...          "details2": {
...             "$filter": {
...                "input": {
...                   "$map": {
...                      "input": "$details1.details2",
...                      "in": {
...                         "details3": {
...                            "$filter": {
...                               "input": "$$this.details3",
...                               "cond": { "$eq": ["$$this.Name", "Bob"] }
...                            }
...                         }
...                      }
...                   }
...                },
...                "cond": { "$ne": ["$$this.details3", []] }
...             }
...          }
...       }
...    }}
... ])

这将产生以下输出-

{ "_id" : ObjectId("5e53ef99f8647eb59e5620a9"), "details1" : { "details2" : [ { "details3" : [ { "Name" : "Bob", "CountryName" : "UK" } ] } ] } }