How to merge two matching objects from different array into one object?

I would like to combine the data in one collection using the IDs of the two arrays.

An example is shown below.

{
    "_id": ObjectId ("5976fd2eb0adec0a32fa9831"),
       "People": [
          {
            "user_id": 1,      <--- ID
            "Name": "Jane",
            "age": 12
          },
          {
            "user_id": 2,      <--- ID
            "Name": "Mark",
            "age": 60
          },
          {
            "user_id": 3,      <--- ID
            "Name": "Tomer",
            "age": 100
          }
       ],
       "Contents": [
          {
            "user_id":  2,   <--- People ID
            "Text": "111"
          },
          {
            "user_id":  1,   <--- People ID
            "Text": "Hi"
          }
       ]
}

and I want to make the above document as below.

{
    "_id": ObjectId ("5976fd2eb0adec0a32fa9831"),
    "People": [
       {
          "user_id": 1,
          "Name" : "Jane",
            "age": 12
       },
       {
          "user_id": 2,
          "Name": "Mark",
            "age": 60
       },
          {
            "user_id": 3,      <--- ID
            "Name": "Tomer",
            "age": 100
          }
    ],
    "Contents": [
       {
          "user_id": 2,
          "Name": "Mark",    <-- Adding
          "Text": "111",

      },
       {
          "user_id": 1,
          "Name": "Jane",    <-- Adding
          "Text": "Hi",

      }
    ]
}

I have tried various things like $lookup or $unwind of .aggregate() but I cannot get the result.

2 Likes

@Daniel_Tourgman have you tired $replaceRoot? I had a similar situation just come up where I merged docs from one collection with objects of an array in a different collection

“$addFields”: {
“Contents”: {
“$map”: {
“input”: “$Contents”,
“as”: “c”,
“in”: {
“user_id”: “$$c.user_id”,
“Text”: “$$c.Text”,
“Name”: {
“$arrayElemAt”: [
“$People.Name”,
{
“$indexOfArray”: [
“$People.user_id”,
“$$c.user_id”
]
},

        ],
        
      },
      
    }
  }
}

}

you can try this method

1 Like

THanks @Niveditha_Rai your answer helped me resolve a long pending problem :slight_smile: