Skip to content

Instantly share code, notes, and snippets.

@chuckntaylor
Last active February 15, 2025 07:41
Show Gist options
  • Save chuckntaylor/ae2af819a1e4d061b373ae6549595022 to your computer and use it in GitHub Desktop.
Save chuckntaylor/ae2af819a1e4d061b373ae6549595022 to your computer and use it in GitHub Desktop.
MongoDB Commands

Copying MongoDB Data

In these examples, we will assume we are copying data from a source database to a destination database.

1. Using mongodump and mongorestore

This is the simplest method.

  1. Dump the source database to a file.
mongodump --uri="your-mongodb-connection-uri" --db=source --out=backup/
  1. Restore the source database to the destination database.
mongorestore --uri="your-mongodb-connection-uri" --db=destination backup/source/

2. Using $out Aggregation

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" } ])

Creating a new field in a collection

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": ""}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment