For this, create two collections and add some document. After that, use $lookup for match. Let us create a collection with documents −
> db.demo101.insertOne( ... { "_id" : "1", "Details" : [ { "PId" : "200" }, { "PId" : "201" }, { "PId" : "201" } ] } ... ) { "acknowledged" : true, "insertedId" : "1" }
Display all documents from a collection with the help of find() method −
> db.demo101.find();
This will produce the following output −
{ "_id" : "1", "Details" : [ { "PId" : "200" }, { "PId" : "201" }, { "PId" : "201" } ] }
Following is the query to create second collection with some documents −
> db.demo102.insertOne( ... { "_id" : "201", "CustEmailId" : "[email protected]" } ... ); { "acknowledged" : true, "insertedId" : "201" }
Display all documents from a collection with the help of find() method −
> db.demo102.find();
This will produce the following output −
{ "_id" : "200", "CustEmailId" : "[email protected]" } { "_id" : "201", "CustEmailId" : "[email protected]" }
Following is the query to aggregate JSON array field for the matching field of other collection −
> 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()
This will produce the following output −
{ "_id" : "1", "Details" : [ { "PId" : "[email protected]" }, { "PId" : "[email protected]" }, { "PId" : "[email protected]" } ] }