MongoDB Cheat Sheet

This MongoDB cheat sheet provides you with the most commonly used MongoDB commands.

Connect to a MongoDB server via the mongosh shell

Connects to the local server 127.0.0.1 with the port 27017 by default:

mongosh

Connect to a server with a user and password, omit the password if you want a prompt:

mongosh --host <host> --port <port> -u <user> -p <pwd>
Code language: HTML, XML (xml)

Connect to the specified host 192.168.1.25 and port 27017:

mongosh "mongodb://192.168.1.25:27017"
Code language: JavaScript (javascript)

Connect to MongoDB service like MongoDB Atlas with a username:

mongosh "mongodb+srv://domain/<dbname>" --username <username>
Code language: HTML, XML (xml)

Disconnect from a server:

exit
Code language: PHP (php)

Databases

Show databases

List all databases in the current database server:

show dbs

Show the current database

Show the name of the current database:

db

Switch database

Switch to another database:

use <database_name>
Code language: HTML, XML (xml)

Collections

List collections in the current database

Show all collections in the current database:

show collections

Drop a collection

Drop the books collection in the current database:

db.books.drop()
Code language: CSS (css)

CRUD

Create

Insert one document into the books collection:

db.books.insertOne({title:'MongoDB Tutorial'})
Code language: CSS (css)

Insert two documents into the books collection:

db.books.insert({title:'MongoDB for Adminstrators'}, {title:'MongoDB for Developers'})
Code language: CSS (css)

Read

Return the first document int the books collection:

db.books.findOne()
Code language: CSS (css)

Return a cursor that show 20 documents, use the it to display more documents:

db.books.find({})
Code language: CSS (css)

Return a book with the title “MongoDB Tutorial”:

db.books.find({title: "MongoDB Tutorial"})
Code language: CSS (css)

Update

db.coll.update({"_id": 1}, {"title": "MongoDB"})
Code language: JavaScript (javascript)

Delete

Delete a single document with the _id 1 from the books collection:

db.books.deleteOne({_id:1});
Code language: CSS (css)

Delete documents whose price is 10 fromthe books collection:

db.books.deleteMany({price: 10})
Code language: CSS (css)

Was this tutorial helpful ?