Lesson 6: Restoring a MongoDB Deployment / Learn

Code Summary: Restoring a MongoDB Deployment

The following code demonstrates how to restore a database from a backup by using mongorestore.

Create a User with the restore role

The following code shows how to create a user that has the restore role, which provides the necessary privileges to restore data from backups:

mongosh admin

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

Use mongorestore to Restore a Database

The following code shows how to use the mongorestore command-line tool to restore a database. Type mongorestore in the command line followed by the options:

  • The --drop option removes any existing collections from the database.
  • The --gzip option is used to restore from a compressed file.
  • The --oplogReplay option replays the oplog entries from the oplog.bson file.
  • The --noIndexRestore option is used to reduce the impact on the system.

The archive option is used to specify the file location of the dump file. In this case, the file location is mongodump-april-2023.

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.

Here's the code:

mongorestore \
--drop \
--gzip \
--oplogReplay \
--noIndexRestore \
--archive=mongodump-april-2023.gz \
“mongodb://restore-admin@mongod0.repleset.com:27017,mongod1.replset.com:27017,mongod2.replset.com:27017/?authSource=admin&replicaSet=replset”