要从子文档数组中获取记录,请使用$unwind和$push。对于从234开始的ID,请在MongoDB中使用regex。
让我们创建一个包含文档的集合-
> db.demo556.insertOne( ... { ... _id:101, ... details:[ ... { ... id:"234336", ... Name:"Chris" ... }, ... { ... id:"123456", ... Name:"Bob" ... }, ... { ... id:"234987", ... Name:"Carol" ... }, ... { ... id:"989768", ... Name:"David" ... }, ... { ... id:"234888", ... Name:"Sam" ... }, ... { ... id:"847656", ... Name:"John" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo556.find();
这将产生以下输出-
{ "_id" : 101, "details" : [ { "id" : "234336", "Name" : "Chris" }, { "id" : "123456", "Name" : "Bob" }, { "id" : "234987", "Name" : "Carol" }, { "id" : "989768", "Name" : "David" }, { "id" : "234888", "Name" : "Sam" }, { "id" : "847656", "Name" : "John" } ] }
以下是从子文档数组中获取记录的查询-
> db.demo556.aggregate({ ... $match: { ... "_id": 101 ... } ... }, { ... $unwind: "$details" ... }, { ... $match: { ... "details.id": { ... $regex: /^234/ ... } ... } ... }, { ... $group: { ... _id: "$_id", ... "Detail": { ... $push: "$details" ... } ... } ... }).pretty();
这将产生以下输出-
{ "_id" : 101, "Detail" : [ { "id" : "234336", "Name" : "Chris" }, { "id" : "234987", "Name" : "Carol" }, { "id" : "234888", "Name" : "Sam" } ] }