mongodb-queryaggregation-frameworkspring-mongodbspring-mongo

Join two collection in mongodb


I'm new in mongodb. Could you please tell me how to perform join operation in this. I've two collection:

Collection 1 ("user")

{
 _id: "d04d53dc-fb88-433e-a1c5-dd41a68d7655",
 userName: "XYZ User",
 age: 12
}

Collection 2 ("square")

{
 _id: "ef6f6ac2-a08a-4f68-a63c-0b4a70285427",
 userId: "d04d53dc-fb88-433e-a1c5-dd41a68d7655",
 side: 4,
 area: 16
}

Now I want to retrieve the data from collection 2 is like this. Expected output:

{
 _id: "ef6f6ac2-a08a-4f68-a63c-0b4a70285427",
 userId: "d04d53dc-fb88-433e-a1c5-dd41a68d7655",
 userName: "XYZ User",
 side: 4,
 area: 16
}

Thanks in advance :)


Solution

  • Here's one way to do it.

    db.square.aggregate([
      {
        "$lookup": {
          "from": "user",
          "localField": "userId",
          "foreignField": "_id",
          "as": "userDoc"
        }
      },
      {
        "$set": {
          "userName": {
            "$first": "$userDoc.userName"
          }
        }
      },
      { "$unset": "userDoc" }
    ])
    

    Try it on mongoplayground.net.