MongoDB 投影到指定的嵌套属性?
对于特定嵌套属性的投影,请在 MongoDB 中使用 aggregate()。让我们先创建一个包含文档的集合 -
> db.demo379.insertOne( ... { ... "details1" : { ... "details2" : { ... "details3" : { ... "10" : "John", ... "50" : "Chris", ... "40" : "David", ... "30":"Mike" ... } ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5a94f82ae06a1609a00b10") }
使用 find() 方法从集合中显示所有文档 -
> db.demo379.find().pretty();
这将生成以下输出 -
{ "_id" : ObjectId("5e5a94f82ae06a1609a00b10"), "details1" : { "details2" : { "details3" : { "10" : "John", "30" : "Mike", "40" : "David", "50" : "Chris" } } } }
以下是针对特定嵌套属性的投影的查询 -
> db.demo379.aggregate([ ... { "$addFields": { ... "details1.details2.details3": { ... "$arrayToObject": { ... "$filter": { ... "input": { "$objectToArray": "$details1.details2.details3" }, ... "as": "out", ... "cond": { ... "$and": [ ... { "$gte": ["$$out.k", "35"] }, ... { "$lte": ["$$out.k", "60"] }, ... ] ... } ... } ... } ... } ... } } ... ])
这将生成以下输出 -
{ "_id" : ObjectId("5e5a94f82ae06a1609a00b10"), "details1" : { "details2" : { "details3" : { "40" : "David", "50" : "Chris" } } } }
广告