为此,创建两个集合并添加一些文档。之后,使用$lookup进行匹配。让我们创建一个包含文档的集合-
> db.demo101.insertOne( ... { "_id" : "1", "Details" : [ { "PId" : "200" }, { "PId" : "201" }, { "PId" : "201" } ] } ... ) { "acknowledged" : true, "insertedId" : "1" }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo101.find();
这将产生以下输出-
{ "_id" : "1", "Details" : [ { "PId" : "200" }, { "PId" : "201" }, { "PId" : "201" } ] }
以下是使用一些文档创建第二个集合的查询-
> db.demo102.insertOne( ... { "_id" : "201", "CustEmailId" : "Carol@gmail.com" } ... ); { "acknowledged" : true, "insertedId" : "201" }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo102.find();
这将产生以下输出-
{ "_id" : "200", "CustEmailId" : "John@gmail.com" } { "_id" : "201", "CustEmailId" : "Carol@gmail.com" }
以下是为其他集合的匹配字段聚合JSON数组字段的查询-
> db.demo101.aggregate( ... [ ... {$unwind:"$Details"}, ... {$lookup : {from : "demo102", "localField":"Details.PId", "foreignField":"_id", as :"out"}}, ... {$project : {"_id":1, "Details.PId":{$arrayElemAt:["$out.CustEmailId",0]}}}, ... {$group:{_id:"$_id", Details : {$push : "$Details"}}} ... ] ... ).pretty()
这将产生以下输出-
{ "_id" : "1", "Details" : [ { "PId" : "John@gmail.com" }, { "PId" : "Carol@gmail.com" }, { "PId" : "Carol@gmail.com" } ] }