基于范围查询 MongoDB 中嵌入式文档的数组?
要基于范围查询嵌入式文档的数组,请使用 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 } ] }
以下是如何按照范围查询 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 } ] }
广告