How to merge collections in mongodb?

Member

by lily , in category: PHP Databases , 8 months ago

How to merge collections in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 3 months ago

@lily 

To merge collections in MongoDB, you can use the aggregate() method with the $merge operator. The $merge operator allows you to insert documents from one collection into another collection, or update existing documents in the target collection with the documents from the source collection.


Here is an example of how you can use the $merge operator to merge two collections in MongoDB:

1
2
3
4
5
6
7
8
9
db.collection1.aggregate([
   {
      $merge: {
         into: "collection2",
         whenMatched: "replace",
         whenNotMatched: "insert"
      }
   }
])


This will insert all documents from collection1 into collection2, replacing any existing documents in collection2 with the same _id, and inserting any new documents that do not exist in collection2.


You can also specify additional pipeline stages to filter and transform the documents before they are inserted or updated in the target collection. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
db.collection1.aggregate([
   {
      $match: {
         status: "active"
      }
   },
   {
      $project: {
         _id: 1,
         name: 1,
         status: 1
      }
   },
   {
      $merge: {
         into: "collection2",
         whenMatched: "replace",
         whenNotMatched: "insert"
      }
   }
])


This will insert only the documents from collection1 that have a status field equal to "active", and will only include the _id, name, and status fields in the documents that are inserted or updated in collection2.


You can find more information about the $merge operator in the MongoDB documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/merge/