MongoDB 查询仅会获得嵌套数组文档中的特定字段?
若要仅在嵌套数组文档中获取特定字段,请将其与 $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" } ] } ] } }
广告