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"
      }
   ]
}

Updated on: 30-Mar-2020

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements