要检索数组中的多个项目,请使用聚合框架。首先让我们创建一个包含文档的集合-
> 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 } ] }