In these examples, we will assume we are copying data from a source database to a destination database.
This is the simplest method.
- Dump the
sourcedatabase to a file.
mongodump --uri="your-mongodb-connection-uri" --db=source --out=backup/- Restore the
sourcedatabase to thedestinationdatabase.
mongorestore --uri="your-mongodb-connection-uri" --db=destination backup/source/If you only need to copy a few collections, you can use the aggregation framework with $out to move documents from one database to another.
Example (for users collection):
db.users.aggregate([ { $match: {} }, { $out: "destination.users" } ])A quick way to add a new field to all documents in a collection is to use the $set operator with an empty query {}.
db.collection.updateMany({}, {$set: {"fieldName": ""}})If the field is a nested field, you can use the dot notation.
db.collection.updateMany({}, {$set: {"nested.fieldName": ""}})