 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB Aggregate JSON array field for the matching field of other collection?
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" : "Carol@gmail.com" } ... ); { "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" : "John@gmail.com" } { "_id" : "201", "CustEmailId" : "Carol@gmail.com" } 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" : "John@gmail.com"       },       {          "PId" : "Carol@gmail.com"       },       {          "PId" : "Carol@gmail.com"       }    ] }Advertisements
 