Lesson 5: Backing Up a MongoDB Deployment / Learn

Code Summary: Backing Up a MongoDB Deployment

Review the following code, which demonstrates how to create a backup by using mongodump.

Create a User with the Backup Role

The following code shows how to connect to the admin database and create a new user with the backup role. The backup role provides the minimum privileges needed for backing up data.

mongosh admin

db.createUser({
   user: "backup-admin",
   pwd: "backup-pass",
   roles: ["backup"]
 })

Use mongodump to Create a Backup

The following code shows how to use the mongodump command-line tool to create a backup. Type mongodump in the command line followed by the options:

  • The oplog option captures incoming write operations during the mongodump operation.
  • The gzip option compresses the output file.
  • The archive option is used to specify the file location for the dump file.

Finally, the cluster has security enabled, so specify the username in the connection string. For self-managed deployments that don't have the SRV specifier, you will need to specify the authSource. The read preference is also set in the connection string to reduce any performance impact.

Here's the code:

mongodump \
--oplog \
--gzip \
--archive=mongodump-april-2023.gz  \
“mongodb://backup-admin@mongod0.repleset.com:27017,mongod1.replset.com:27017,mongod2.replset.com:27017/?authSource=admin&replicaSet=replset&readPreference=secondary”

Create a Backup for a Specific Collection

Use the --db and --collection options to create a backup of a specific collection in a database. The --db option can be specified as a command-line argument or as part of the connection string.

Here’s an example:

--collection=neighborhoods \
--gzip \
--archive=mongodump-neighborhoodss-2023.gz \
"mongodb://backup-admin:@mongod0.repleset.com:27017,mongod1.replset.com:27017,mongod2.replset.com:27017/sample_restaurants?authSource=admin&replicaSet=replset"