shell

Master MongoDB with our comprehensive shell cheatsheet. Learn essential commands for database management, data manipulation, backups, and restores.

MongoDB Shell Cheatsheet

MongoDB Shell Commands and Examples

This cheatsheet provides essential MongoDB commands using the mongo shell, covering database management, data manipulation, and operational tasks like backups and restores.

Table of Contents

Definitions

  • A field in MongoDB: {"key": "value"}
  • A field consists of a key and a value.
  • Operators like $gt (greater than) or $lt (less than) can be used for querying.

Setting Up MongoDB Shell

Create a MongoDB instance using Docker and connect to the shell:

docker run --rm -itd --name mongodb -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=password -p 27017:27017 mongo:4.4
docker exec -it mongodb mongo -u "root" -p "password" --authenticationDatabase "admin"
> 

Managing Databases

View existing databases:

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

Create or switch to a database:

> use mydb
switched to db mydb

View the current database:

> db
mydb

Managing Collections

Create a collection:

> db.createCollection("mycol1")
{ "ok" : 1 }
> db.createCollection("mycol2")
{ "ok" : 1 }

View collections:

> show collections
mycol1
mycol2

Writing Data to MongoDB

Insert data into a collection:

> db.mycol1.insert({"name": "ruan", "age": 32, "hobbies": ["golf", "programming", "music"]})
WriteResult({ "nInserted" : 1 })
> db.mycol1.insert({"name": "michelle", "age": 28, "hobbies": ["art", "music", "reading"]})
WriteResult({ "nInserted" : 1 })

Reading Data from MongoDB

Read all data from a collection (similar to SELECT * FROM mycol1):

> db.mycol1.find()
{ "_id" : ObjectId("5cc60c8ebdbf7f5dd3f7cdc3"), "name" : "ruan", "age" : 32, "hobbies" : [ "golf", "programming", "music" ] }
{ "_id" : ObjectId("5cc60cacbdbf7f5dd3f7cdc4"), "name" : "michelle", "age" : 28, "hobbies" : [ "art", "music", "reading" ] }

Using pretty printing for better readability:

> db.mycol1.find().pretty()
{
    "_id" : ObjectId("5cc60c8ebdbf7f5dd3f7cdc3"),
    "name" : "ruan",
    "age" : 32,
    "hobbies" : [
        "golf",
        "programming",
        "music"
    ]
}
{
    "_id" : ObjectId("5cc60cacbdbf7f5dd3f7cdc4"),
    "name" : "michelle",
    "age" : 28,
    "hobbies" : [
        "art",
        "music",
        "reading"
    ]
}

Select specific fields (name and age), similar to SELECT name, age FROM mycol1:

> db.mycol1.find({}, {"name": 1, "age": 1, "_id": 0})
{ "name" : "ruan", "age" : 32 }
{ "name" : "michelle", "age" : 28 }

Select data where age equals 32, similar to SELECT name, age FROM mycol1 WHERE age = 32:

> db.mycol1.find({"age": 32}, {"name": 1, "age": 1, "_id": 0})
{ "name" : "ruan", "age" : 32 }

Return the name from a specific document ID, similar to SELECT name FROM mycol1 WHERE id = xx:

db.mycol1.findOne({_id: ObjectId("5cc60c8ebdbf7f5dd3f7cdc3")}).name ruan

Find documents older than a specific age (e.g., age greater than 30):

> db.mycol1.find({"age": {"$gt": 30}})
{ "_id" : ObjectId("5cc60c8ebdbf7f5dd3f7cdc3"), "name" : "ruan", "age" : 32, "hobbies" : [ "golf", "programming", "music" ] }

Backing Up MongoDB

Mongodump using URI syntax:

mongodump --uri="mongodb://uberuser:passherd@localhost:27107/redbase?ssl=false&authSource=admin"

Mongodump using standard flags:

mongodump --user=uberuser --db=redbase --password=passherd --authenticationDatabase=admin

Specify the output directory:

mongodump --user=uberuser --db=redbase --password=passherd --authenticationDatabase=admin --out=dumbbase

Dump only a specific collection:

mongodump --user=ubersuser --db=redbase --password=passherd --authenticationDatabase=admin --out=dumbbase --collection=action_figures

The backup structure will look like this:

.
 |_dumbbase
   |_redbase
     |_action_figures.metadata.json
     |_action_figures.bson

Dump all databases into an archive:

mongodump --db=redbase --username=uberuser --password=passherd --authenticationDatabase=admin --archive=redbase.archive

Restoring MongoDB

Restore from a dump directory. This command will not overwrite documents with the same ID:

mongorestore dump/

To restore only a specific collection:

mongorestore --db=newdb --collection=comic_books dump/mydb/product.bson

A better approach is to use --nsInclude:

mongorestore --db=redbase --nsInclude="db1.*" dump/

External Resources