在 MongoDB 中检索数组中的多个项目的查询?
要检索数组中的多个项目,请使用聚合框架。我们先创建一个带有文档的集合 −
> db.retrieveMultipleDemo.insertOne( ... { ... "UserDetails": ... [ ... { "_id": "101", "UserName":"John", "UserAge": 23 }, ... { "_id": "102", "UserName":"Carol", "UserAge": 21 }, ... { "_id": "103", "UserName":"David", "UserAge": 23}, ... { "_id": "104", "UserName":"Sam", "UserAge": 25} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd40c85edc6604c74817cf0") }
以下是使用 find() 方法显示集合中所有文档的查询 −
> db.retrieveMultipleDemo.find().pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cd40c85edc6604c74817cf0"), "UserDetails" : [ { "_id" : "101", "UserName" : "John", "UserAge" : 23 }, { "_id" : "102", "UserName" : "Carol", "UserAge" : 21 }, { "_id" : "103", "UserName" : "David", "UserAge" : 23 }, { "_id" : "104", "UserName" : "Sam", "UserAge" : 25 } ] }
以下是检索数组中多个项目的查询 −
> db.retrieveMultipleDemo.aggregate([ ... {$unwind:"$UserDetails"}, ... {$match:{"UserDetails._id":{$in:myIds},"UserDetails.UserAge":23}}, ... {$group:{"_id":"_id","UserDetails":{$push:"$UserDetails"}}}, ... {$project:{"_id":0,"UserDetails":1}} ... ]);
这将产生以下输出 −
{ "UserDetails" : [ { "_id" : "101", "UserName" : "John", "UserAge" : 23 }, { "_id" : "103", "UserName" : "David", "UserAge" : 23 } ] }
广告