Srinivas
Srinivas

Reputation: 909

How to combine multiple collections and merge the joined documents into a single document

Here is the problem, I am unable to get the following result. Please look into the piece of json and help me out.

This is my data:

[
  {
    "user_id": "65asdfksadjfk3u4",
    "lat": 23.4343,
    "long": 15.2382 
  }
]

Currently my result is:

[
  {
    "_id": "65asdfksadjfk3u4",
    "name": "Srini",
    "age": 26,
    "some other key": "some other values"
  }
]

I need to get the collection from the user_id and add it to the same array object. As you can notice both lat and long are being removed in my current result.

[
  {
     "_id": "65asdfksadjfk3u4",
     "name": "Srini",
     "age": 26,
     "some other keys": "some other values",
     "lat": 23.4343,
     "long": 15.2382 
  }
]

Upvotes: 1

Views: 122

Answers (1)

chridam
chridam

Reputation: 103365

You can append the $lookup stage to join the current pipeline results with the users collections by the user_id fields and then use $mergeObjects in the $replaceRoot to merge the joined documents from users and the current results:

db.collection.aggregate([
    /* current pipeline here */
    { "$lookup": {
            "from": "users",
            "localField": "_id",
            "foreignField": "user_id",
            "as": "user"
    } },
    { "$replaceRoot": { 
        "newRoot": { 
            "$mergeObjects": [ 
                { "$arrayElemAt": [ "$user", 0 ] }, 
                "$$ROOT" 
             ] 
        } 
    } },
    { "$project": { "user": 0, "user_id": 0 } }    
]);

Upvotes: 1

Related Questions