MongoDB cheat sheet

Data management

Commands to run as an admin user after running this to select a database:

use REPLACE_DATABASE_NAME

Get all the collections

show collections

Drop a collection

db.replaceCollectionName.drop()

Delete all the collections

db.getCollectionNames().forEach(function(c) { if (c.indexOf(“system.”) == -1) db[c].drop(); }

User management

Commands to run as admin user after running this to select a database:

use REPLACE_DATABASE_NAME

Get the list of users and their configuration

Get the details of all the users:

db.getUsers()

Get the details of a specific user:

db.getUser(“REPLACE_USERNAME”)”

We can get additional details providing an extra param:

db.getUser(“REPLACE_USERNAME”, { showAuthenticationRestrictions: true })

Delete a user

db.dropUser(“REPLACE_USERNAME”)

Create a user

Run this command specifying the username, password, etc. The auth mechanism should be SCRAM-SHA-256 unless it is an old version that only works with SCRAM-SHA-1 (before 4.x).

db.createUser({
“user” : “REPLACE_USERNAME”,
“pwd” : “REPLACE_PASSWORD”,
“mechanisms” : [“REPLACE_AUTH_MECHANISM”],
“roles” : […],
“authenticationRestrictions” : [ ] })

Backups

Create a backup

mongodump –host REPLACE_SERVER_URL –port REPLACE_PORT –db barracuda –authenticationDatabase REPLACE_DATABASE_NAME –username REPLACE_USERNAME –collection REPLACE_COLLECTION_NAME –out REPLACE_BACKUP_FILE_NAME

The –collection parameter is optional, the tool will export all the collections if it is not specified.

Restore a database from a backup

mongorestore –host REPLACE_SERVER_URL –port REPLACE_PORT –db REPLACE_DATABASE_NAME –username REPLACE_USERNAME REPLACE_PATH_UNCOMPRESSED_BACKUP_FOLDER

Restore a collection from a backup

mongorestore –host REPLACE_SERVER_URL –port REPLACE_PORT –db REPLACE_DATABASE_NAME –authenticationDatabase REPLACE_DATABASE_NAME –username REPLACE_USERNAME –collection REPLACE_COLLECTION_NAME REPLACE_PATH_BSON_FILE

Other

Change database max memory setting

We can configure this setting: wiredTigerCacheSizeGB

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>