Afikasky
Afikasky

Reputation: 133

Copy data from one collection into another - MongoDB

I'd like to copy data from one collection (collection A) into another (collection B) using MongoDB. I'd also like to keep the existing data in collection A. [I'm using MongoDB shell version v4.4.3, GoormIDE with a Node.js and Express app)

From what I understand the $merge operator will be the most appropriate, however I keep running into an error. I have been using the code below:

db.getSiblingDB("<databasename>").<sourcecollection>.aggregate( [     { $match : {} },     { $merge : "<destinationnewcollection>" } ] )

This is the resulting error:

   uncaught exception: Error: command failed: {
        "ok" : 0,
        "errmsg" : "Failed to retrieve database or collection name from $merge. err=Error parsing $merge value.


     "code" : 8000,
        "codeName" : "AtlasError"
} : aggregate failed :

Other operators such as add seem to work fine so I am lost for ideas on this one. Any ideas of what I'm doing wrong?

Upvotes: 2

Views: 766

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59456

According documentation { $merge : "<destinationnewcollection>" } should work. However, looks like the short form is not available, so use

db.getSiblingDB("<databasename>").<sourcecollection>.aggregate([
   { $unset: "_id" },
   { $merge: { into: "<destinationnewcollection>" } } 
])

or

db.getSiblingDB("<databasename>").<sourcecollection>.aggregate([
   { $unset: "_id" },
   { $merge: { into: { db: "<databasename>", coll: "<destinationnewcollection>" } } } 
])

You can skip { $match : {} } - it does nothing. Removing the _id field ensures that all documents are added in any case, it also should speed up the operation.

Upvotes: 3

Related Questions