I have arrays of two different collections and I want to join some fields from both collections based on there ID's

I have arrays of two different collections and I want to join some fields from both collections based on there ID’s

data :[
{
_id:“1”,
_descriptionID:“11”,
last_date:null,
next_data:null
},
{
_id:“2”,
_descriptionID:“22”,
last_date:null,
next_data:null
},
]
description:[
{
_id:“11”,
description_name:“test”
},
{
_id:“22”,
description_name:“actual”
}]

I want the output as:
data_description:[
{
_id:“1”,
_descriptionID:“11”,
last_date:null,
next_data:null,
description_name:“test”
},
{
_id:“2”,
_descriptionID:“22”,
last_date:null,
next_data:null,
description_name:“actual”
}
]
I am struggle from past 1 day, any help in this regard is highly appreciated.

You can do it with Aggregation Framework:

  • $lookup - to fetch data from description collection based on _descriptionID
  • $set with $first - since the $lookup returns an array, to fetch the first item of that array and put it in description property
  • $set - to description_name
  • $project - to select all the fields that should be returned
db.data.aggregate([
  {
    "$lookup": {
      "from": "description",
      "localField": "_descriptionID",
      "foreignField": "_id",
      "as": "description",
      
    }
  },
  {
    "$set": {
      "description": {
        "$first": "$description"
      }
    }
  },
  {
    "$set": {
      "description_name": "$description.description_name"
    }
  },
  {
    "$project": {
      "_id": 1,
      "_descriptionID": 1,
      "last_date": 1,
      "next_data": 1,
      "description_name": 1
    }
  }
])

Working example

Hi, Thank you so much for the reply… This is exactly what I want. But on real working example it is giving me error . “Unrecognized expression ‘$first’”… Why is this for ?

Can you copy your query?