MongoDB 8 cheatsheet

MongoDB 8: Backup and administration

8 common MongoDB 8 tasks.

Back up a database

Write a binary dump of one database to a folder.

mongodump --uri="mongodb://localhost:27017/mydb" --out=backup/

Restore a dump

Restore a dump into a server.

mongorestore --uri="mongodb://localhost:27017" backup/

Caution: Restoring can overwrite documents with the same _id. Use --drop only when you mean to replace existing collections.

Export a collection to JSON

Write a collection to a JSON file.

mongoexport --uri="mongodb://localhost:27017/mydb" --collection=users --out=users.json

Import JSON

Load a JSON file into a collection.

mongoimport --uri="mongodb://localhost:27017/mydb" --collection=users --file=users.json

Check database size

Show the data size, storage size and index size.

db.stats()

Create a user

Create a user with read and write access to one database. Use a real password.

db.createUser({ user: "appUser", pwd: "change-me", roles: [{ role: "readWrite", db: "mydb" }] })

Drop a collection

Delete a collection and its indexes.

db.users.drop()

Caution: Permanently deletes the collection. Back it up first.

Drop the current database

Delete the current database.

db.dropDatabase()

Caution: Permanently deletes every collection in the current database. Check which database you are on with db.

Was this page helpful?