要根据范围查询嵌入式文档的数组,请使用aggregate()
。让我们创建一个包含文档的集合-
> db.demo346.insertOne( ... { ... _id: 101, ... userDetails: [ ... { UserName: "Chris", Score:78}, ... { UserName: "David", Score:68}, ... { UserName: "Bob", Score:88} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 } > db.demo346.insertOne( ... { ... _id: 102, ... userDetails: [ ... { UserName: "Mike", Score:92}, ... { UserName: "Sam", Score:62}, ... { UserName: "Carol", Score:97} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 102 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo346.find();
这将产生以下输出-
{ "_id" : 101, "userDetails" : [ { "UserName" : "Chris", "Score" : 78 }, { "UserName" : "David", "Score" : 68 }, { "UserName" : "Bob", "Score" : 88 } ] } { "_id" : 102, "userDetails" : [ { "UserName" : "Mike", "Score" : 92 }, { "UserName" : "Sam", "Score" : 62 }, { "UserName" : "Carol", "Score" : 97 } ] }
以下是如何根据Range在MongoDB中查询嵌入式文档的数组-
> db.demo346.aggregate([ ... { "$match": { "$expr": { "$gte": [{ "$size": { "$ifNull": ["$userDetails", []] } }, 1] }}}, ... { "$addFields": { ... "userDetails": { ... "$filter": { ... "input": { "$ifNull": ["$userDetails", []] }, ... "cond": { ... "$and": [ ... { "$gte": ["$$this.Score", 80] }, ... { "$lte": ["$$this.Score", 99] } ... ] ... } ... } ... } ... }} ... ])
这将产生以下输出-
{ "_id" : 101, "userDetails" : [ { "UserName" : "Bob", "Score" : 88 } ] } { "_id" : 102, "userDetails" : [ { "UserName" : "Mike", "Score" : 92 }, { "UserName" : "Carol", "Score" : 97 } ] }