How to Merge Documents when Importing a File into MongoDB

When you use mongoimport to import files into MongoDB, you have the option of merging existing documents with the ones that you’re importing.

In this case, if an imported document has the same _id value as an existing one in the collection that you’re importing into, the existing document will be merged with the one being imported.

You can also specify another field (other than the _id field) to be the matching field if required.

Continue reading

How to Replace Existing Documents when Importing a File into MongoDB

When you use mongoimport to import files into MongoDB, you have the option of replacing existing documents that match the ones you’re importing.

By this I mean, if an imported document has the same _id value as an existing one in the collection you’re importing into, the existing document will be replaced with the one being imported.

You can also specify another field (other than the _id field) to be the matching field if required.

The way to replace existing documents when using mongoimport is to use upsert mode.

Continue reading

Copy/Clone a Database in MongoDB

In earlier versions of MongoDB, you could use the copyDB command or its helper method, db.copyDatabase() to copy a database.

MongoDB has since deprecated these. Also, starting in version 4.2, MongoDB has removed the copydb command, and therefore also the db.copyDatabase() method, which means that you can’t use them even if you wanted to if you’re using MongoDB 4.2 or later.

Fortunately, there’s another way to copy a MongoDB database.

Continue reading