How to join two collection in mongodb?

Member

by rollin , in category: MySQL , a day ago

How to join two collection in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 4 hours ago

@rollin 

In MongoDB, you can join two collections by using the aggregation framework and the $lookup operator. Here is an example of how you can join two collections:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
db.collection1.aggregate([
  {
    $lookup: {
      from: "collection2",
      localField: "field_in_collection1",
      foreignField: "field_in_collection2",
      as: "joined_data"
    }
  }
])


In this example, replace "collection1" and "collection2" with the names of your collections. Also, replace "field_in_collection1" and "field_in_collection2" with the fields that you want to use to join the two collections.


The $lookup operator will match the documents in collection1 with the documents in collection2 based on the specified fields and add the matching documents as an array to the "joined_data" field in the output.