从 MongoDB 中的子文档数组中提取 id 从 234 开始的记录
若要从子文档数组中提取记录,请使用$unwind 和$push。对于从 234 开始的 id,请在 MongoDB 中使用正则表达式。
我们使用文档创建一个集合−
> 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" } ] }
广告