Cheatsheets

MongoDB Cheat Sheet – Complete Command Reference Guide 2026

Complete MongoDB cheat sheet with 200+ commands, queries, operators & examples. Covers CRUD operations, aggregation pipeline, indexing, backup/restore. Perfect for developers & DBAs.

🍃 MongoDB Cheat Sheet

Complete Reference Guide - Commands, Queries & Operators

No results found. Try a different search term.

Getting Started & Connection

mongosh

Start MongoDB shell (modern version - recommended for MongoDB 4.4+)

mongo

Start MongoDB shell (legacy version)

mongosh "mongodb://localhost:27017"

Connect to local MongoDB server on default port

mongosh "mongodb+srv://cluster.mongodb.net/dbname" --username <user>

Connect to MongoDB Atlas cluster (cloud database)

mongosh --host <host> --port <port> -u <user> -p <pwd>

Connect with authentication credentials

exit

Exit MongoDB shell

Database Commands

show dbs

List all databases on the MongoDB server

show databases

List all databases (alternative command)

db

Display current database name

use <database_name>

Switch to database (creates if doesn't exist)

use myDatabase
db.dropDatabase()

Drop (delete) the current database

db.stats()

Display statistics about the current database

Collection Commands

show collections

List all collections in current database

db.createCollection("collection_name")

Create a new empty collection

db.createCollection("users")
db.collection_name.drop()

Drop (delete) a collection

db.users.drop()
db.collection_name.renameCollection("new_name")

Rename an existing collection

db.oldName.renameCollection("newName")
db.collection_name.stats()

Display statistics about the collection

CRUD Operations - Create (Insert)

db.collection.insertOne({field: "value"})

Insert a single document into collection

db.users.insertOne({name: "John Doe", age: 30, email: "john@example.com"})
db.collection.insertMany([{...}, {...}])

Insert multiple documents at once

db.users.insertMany([ {name: "Alice", age: 25}, {name: "Bob", age: 35} ])
db.collection.insert({field: "value"})

Insert document (legacy method - use insertOne/insertMany)

db.collection.insertMany([...], {ordered: false})

Unordered bulk insert (continues on error)

CRUD Operations - Read (Query)

db.collection.find()

Retrieve all documents from collection

db.collection.find().pretty()

Display results with formatted JSON output

db.collection.findOne()

Retrieve the first matching document

db.collection.find({field: value})

Find documents matching specific criteria

db.users.find({age: 25})
db.collection.find({field: {$operator: value}})

Find with comparison operators

db.users.find({age: {$gt: 18}})
db.collection.find({}, {field1: 1, field2: 1})

Projection - return only specified fields

db.users.find({}, {name: 1, email: 1, _id: 0})
db.collection.find().limit(n)

Limit results to n documents

db.users.find().limit(10)
db.collection.find().skip(n)

Skip first n documents

db.users.find().skip(5)
db.collection.find().sort({field: 1})

Sort results: 1 for ascending, -1 for descending

db.users.find().sort({age: -1})
db.collection.count()

Count all documents in collection

db.collection.countDocuments({filter})

Count documents matching filter criteria

db.users.countDocuments({age: {$gt: 18}})

CRUD Operations - Update

db.collection.updateOne({filter}, {$set: {field: value}})

Update first matching document

db.users.updateOne({name: "John"}, {$set: {age: 31}})
db.collection.updateMany({filter}, {$set: {field: value}})

Update all matching documents

db.users.updateMany({age: {$lt: 18}}, {$set: {minor: true}})
db.collection.replaceOne({filter}, {newDocument})

Replace entire document (except _id)

db.users.replaceOne({_id: 1}, {name: "New User", age: 25})
db.collection.updateOne({filter}, {$set: {...}}, {upsert: true})

Update if exists, insert if not (upsert operation)

db.users.updateOne({email: "new@example.com"}, {$set: {name: "New"}}, {upsert: true})
db.collection.findAndModify({query: {...}, update: {...}})

Find and modify document atomically

CRUD Operations - Delete

db.collection.deleteOne({filter})

Delete first matching document

db.users.deleteOne({name: "John"})
db.collection.deleteMany({filter})

Delete all matching documents

db.users.deleteMany({age: {$lt: 18}})
db.collection.deleteMany({})

Delete all documents (keep collection structure)

db.collection.remove({filter})

Remove documents (legacy - use deleteOne/deleteMany)

Query Operators - Comparison

$eq

Equal to - matches values that are equal to specified value

{age: {$eq: 25}}
$ne

Not equal to - matches values that are not equal

{status: {$ne: "inactive"}}
$gt

Greater than - matches values greater than specified value

{age: {$gt: 18}}
$gte

Greater than or equal to

{score: {$gte: 80}}
$lt

Less than - matches values less than specified value

{age: {$lt: 65}}
$lte

Less than or equal to

{price: {$lte: 100}}
$in

Match any value in array

{status: {$in: ["active", "pending", "approved"]}}
$nin

Not match any value in array

{status: {$nin: ["deleted", "banned"]}}

Query Operators - Logical

$and

Join query clauses with logical AND

{$and: [{age: {$gt: 18}}, {status: "active"}]}
$or

Join query clauses with logical OR

{$or: [{age: {$lt: 18}}, {age: {$gt: 65}}]}
$not

Inverts the effect of query expression

{age: {$not: {$gt: 18}}}
$nor

Join query clauses with logical NOR (opposite of OR)

{$nor: [{status: "active"}, {age: {$lt: 18}}]}

Query Operators - Element

$exists

Match documents that have the specified field

{email: {$exists: true}}
$type

Match documents where field is of specified BSON type

{age: {$type: "number"}}

Query Operators - Evaluation

$regex

Match documents using regular expressions

{name: {$regex: /^J/, $options: "i"}}
$text

Perform text search on indexed fields

{$text: {$search: "coffee shop"}}
$where

Match documents using JavaScript expression

{$where: "this.age > 18"}
$expr

Use aggregation expressions in queries

{$expr: {$gt: ["$spent", "$budget"]}}
$mod

Perform modulo operation on field value

{qty: {$mod: [4, 0]}}

Query Operators - Array

$all

Match arrays containing all specified elements

{tags: {$all: ["red", "blue"]}}
$elemMatch

Match array elements that satisfy all conditions

{results: {$elemMatch: {$gte: 80, $lt: 85}}}
$size

Match arrays with specified size

{tags: {$size: 3}}

Update Operators

$set

Set the value of a field in document

{$set: {age: 30, status: "active"}}
$unset

Remove specified field from document

{$unset: {middleName: ""}}
$inc

Increment field value by specified amount

{$inc: {age: 1, views: 5}}
$mul

Multiply field value by specified number

{$mul: {price: 1.1}}
$rename

Rename a field

{$rename: {"oldName": "newName"}}
$min

Update field only if specified value is less than current

{$min: {lowScore: 50}}
$max

Update field only if specified value is greater than current

{$max: {highScore: 100}}
$currentDate

Set field to current date/timestamp

{$currentDate: {lastModified: true}}

Array Update Operators

$push

Add element to array

{$push: {tags: "new-tag"}}
$pop

Remove first (-1) or last (1) element from array

{$pop: {tags: 1}}
$pull

Remove all matching elements from array

{$pull: {tags: "old-tag"}}
$addToSet

Add element to array only if it doesn't exist (unique)

{$addToSet: {tags: "unique-tag"}}
$pullAll

Remove all specified values from array

{$pullAll: {tags: ["tag1", "tag2", "tag3"]}}

Aggregation Pipeline Stages

$match

Filter documents (like WHERE in SQL)

db.orders.aggregate([ {$match: {status: "completed"}} ])
$group

Group documents by specified expression

db.orders.aggregate([ {$group: {_id: "$category", total: {$sum: "$amount"}}} ])
$project

Reshape documents (include/exclude fields)

{$project: {name: 1, age: 1, _id: 0}}
$sort

Sort documents by specified fields

{$sort: {age: -1, name: 1}}
$limit

Limit number of documents in pipeline

{$limit: 10}
$skip

Skip specified number of documents

{$skip: 5}
$unwind

Deconstruct array field into separate documents

{$unwind: "$tags"}
$lookup

Perform left outer join with another collection

{$lookup: { from: "orders", localField: "_id", foreignField: "userId", as: "userOrders" }}
$out

Write aggregation results to new collection

{$out: "aggregated_results"}
$count

Count documents in pipeline

{$count: "totalDocuments"}

Aggregation Accumulator Operators

$sum

Calculate sum of numeric values

{$group: {_id: "$category", total: {$sum: "$amount"}}}
$avg

Calculate average of numeric values

{$group: {_id: "$category", avgScore: {$avg: "$score"}}}
$min

Get minimum value from group

{$group: {_id: "$category", minPrice: {$min: "$price"}}}
$max

Get maximum value from group

{$group: {_id: "$category", maxPrice: {$max: "$price"}}}
$first

Get first value in group

{$group: {_id: "$category", firstName: {$first: "$name"}}}
$last

Get last value in group

{$group: {_id: "$category", lastName: {$last: "$name"}}}
$push

Create array from all values in group

{$group: {_id: "$category", items: {$push: "$item"}}}
$addToSet

Create array of unique values in group

{$group: {_id: "$category", uniqueItems: {$addToSet: "$item"}}}

Index Commands

db.collection.createIndex({field: 1})

Create ascending index on field (1 = ascending, -1 = descending)

db.users.createIndex({email: 1})
db.collection.createIndex({field: -1})

Create descending index on field

db.collection.createIndex({field1: 1, field2: -1})

Create compound index on multiple fields

db.users.createIndex({lastName: 1, firstName: 1})
db.collection.createIndex({field: "text"})

Create text index for full-text search

db.articles.createIndex({content: "text"})
db.collection.createIndex({field: 1}, {unique: true})

Create unique index (no duplicate values)

db.collection.getIndexes()

List all indexes on collection

db.collection.dropIndex("index_name")

Drop specific index by name

db.collection.dropIndexes()

Drop all indexes except _id index

db.collection.find().explain("executionStats")

Analyze query performance and index usage

BSON Data Types

String

UTF-8 encoded text data

{name: "John Doe"}
Integer (32-bit)

Whole numbers (-2³¹ to 2³¹-1)

{count: 100}
Integer (64-bit)

Large whole numbers (-2⁶³ to 2⁶³-1)

{population: 9876543210}
Double

64-bit IEEE 754 floating point numbers

{price: 19.99, pi: 3.14159}
Boolean

True or false values

{isActive: true, verified: false}
Date

Date and time (stored as milliseconds since Unix epoch)

{createdAt: ISODate("2024-01-15T10:30:00Z")}
Null

Null value or nonexistent field

{middleName: null}
Object

Embedded document (nested object)

{address: {street: "123 Main St", city: "NYC"}}
Array

Ordered list of values

{tags: ["mongodb", "database", "nosql"]}
ObjectId

12-byte unique document identifier (default _id type)

{_id: ObjectId("507f1f77bcf86cd799439011")}
Binary

Binary data for storing files and byte arrays

{file: BinData(0, "base64encodeddata")}
RegExp

Regular expression patterns

{pattern: /^[A-Z]/i}
Timestamp

Internal MongoDB timestamp (for replication/sharding)

{ts: Timestamp(1, 1)}

Backup & Restore Commands

mongodump

Create binary backup of all databases

mongodump --db <dbname>

Backup specific database

mongodump --db myDatabase
mongodump --db <dbname> --collection <collname>

Backup specific collection

mongodump --db myDatabase --collection users
mongodump --out /backup/path

Specify custom backup directory

mongorestore

Restore all databases from backup

mongorestore --db <dbname> /path/to/backup

Restore specific database

mongorestore --drop

Drop existing collections before restoring

mongodump --archive | mongorestore --archive

Pipe backup directly to restore (useful for migrations)

mongodump --host <host> --port <port> -u <user> -p <pwd>

Backup from remote authenticated server

Administration & Monitoring

db.serverStatus()

Get comprehensive server status and metrics

db.currentOp()

Display currently running operations

db.killOp(<opid>)

Terminate specific operation by operation ID

db.getCollectionNames()

Return array of all collection names

db.getUsers()

List all users in current database

db.shutdownServer()

Shutdown MongoDB server (requires admin privileges)

db.version()

Display MongoDB server version

db.hostInfo()

Get system and host information

db.isMaster()

Check replication status and role

💡 Quick Tips & Best Practices

✓ Always create indexes on frequently queried fields to improve performance
✓ Use projection to return only needed fields: db.collection.find({}, {name: 1, email: 1, _id: 0})
✓ Aggregation pipeline processes data in stages for complex transformations and analytics
✓ Use explain() to analyze query performance and optimize slow queries
✓ Connection string format: mongodb://[username:password@]host[:port][/database]
✓ Use $lookup for joining collections (similar to SQL JOIN operations)
✓ BSON (Binary JSON) is MongoDB's native format - supports more data types than JSON
✓ Always backup databases before performing production operations or major updates
✓ Use compound indexes for queries that filter on multiple fields
✓ Limit and skip operations should be used with caution on large datasets

📚 About This Cheatsheet

This comprehensive MongoDB cheatsheet covers essential commands, operators, and best practices for developers and database administrators. Created with MongoDB 4.4+ in mind.

Author: Expert MongoDB Developer | Last Updated: 2025

For more MongoDB resources and tutorials, visit official MongoDB documentation.

Shares: