0

Have two collections

contact_details :

{_id:ObjectId("abcd1234"),
name:"elmaro",
email:"elmaro@gmail.com"}

loaction_details:

{_id:ObjectId("aasd234gas"),
contact_id:ObjectId("abcd1234"),
location:"Ohio"}

how to use aggregate function to transform data into this

Merged_data:


{contact_id:ObjectId("abcd1234"),
location:"Ohio",
name:"elmaro",
email:"elmaro@gmail.com"}

Valijon
  • 12,667
  • 4
  • 34
  • 67
theUnknown
  • 263
  • 1
  • 3
  • 12

1 Answers1

0

You need to use $lookup operator to join contact_details and loaction_details collections and $project to transform the result.

db.contact_details.aggregate([
    {$lookup:{
         from:"loaction_details",
         localField:"_id",
         foreignField:"contact_id",
         as : "location"
     }},
     {$unwind:"$location"},
     {$project:{
         _id:0,
         name:1,
         email:1,
         contact_id:"$location.contact_id",
         location:"$location.location"
      }}
])
Valijon
  • 12,667
  • 4
  • 34
  • 67
  • This will work fine if there is a document available in **location_details** collection for every document exist in **contact_details** collection. Otherwise, you should use $unwind with **preserveNullAndEmptyArrays** option. If there is any document that doesn't have a match in **location_details** then after unwinding the array, this option will preserve that document within the result. Otherwise, such documents will be skipped from the result. – Abhinandan Kothari Jan 08 '20 at 09:57