-1

Let's say we have two collections (user & data) and need to pull all the data for each user_id from users & data collection.

users
     {user_id: 1, username: tom, userage: 27}
     {user_id: 2, username: sam, userage: 25}

data
     {workexp: 4, skill: testing, user_id: 1}
     {workexp: 9, skill: devops, user_id: 2}

Please tell me how we can perform this in mongo.

  • 2
    Possible duplicate of [How do I perform the SQL Join equivalent in MongoDB?](https://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb) – Ashh Sep 18 '18 at 09:03

1 Answers1

0

You can join collections using lookup operator.

Read documentation here: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

Example:

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

in your situation something like this:

db.users.aggregate([
    {
        $lookup: {
           from: "data",
           localField: "user_id",
           foreignField: "user_id",
           as: "user_data"
        }
    }])

This returns this JSON object:

{
    "_id" : ObjectId("5ba0bace2fd0cdd3eae35df6"),
    "user_id" : 1,
    "username" : "tom",
    "userage" : 27,
    "user_data" : [ 
        {
            "_id" : ObjectId("5ba0bafe2fd0cdd3eae35e16"),
            "workexp" : 4,
            "skill" : "testing",
            "user_id" : 1
        }
    ]
}
danyolgiax
  • 12,798
  • 10
  • 65
  • 116