How to join more than 2 collections in mongodb?

by elisha_langworth , in category: MySQL , a month ago

How to join more than 2 collections in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , a month ago

@elisha_langworth 

In MongoDB, you can join more than 2 collections using the $lookup aggregation pipeline stage. Here's an example of how you can join three collections:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
db.collection1.aggregate([
  {
    $lookup: {
      from: "collection2",
      localField: "field1",
      foreignField: "field2",
      as: "first_join"
    }
  },
  {
    $unwind: "$first_join"
  },
  {
    $lookup: {
      from: "collection3",
      localField: "first_join.field3",
      foreignField: "field4",
      as: "second_join"
    }
  },
  {
    $unwind: "$second_join"
  }
])


In this example, we first join collection1 and collection2 using the fields field1 and field2. Then we unwind the result of the first join and join the result with collection3 using the fields field3 and field4.


You can continue adding more $lookup stages to join additional collections as needed. Remember to use $unwind after each join to flatten the array of results before proceeding to the next join stage.