🍃 MongoDB Cheat Sheet
Complete Reference Guide - Commands, Queries & Operators
Getting Started & Connection ▼
mongoshStart MongoDB shell (modern version - recommended for MongoDB 4.4+)
mongoStart 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
exitExit MongoDB shell
Database Commands ▼
show dbsList all databases on the MongoDB server
show databasesList all databases (alternative command)
dbDisplay current database name
use <database_name>Switch to database (creates if doesn't exist)
use myDatabasedb.dropDatabase()Drop (delete) the current database
db.stats()Display statistics about the current database
Collection Commands ▼
show collectionsList 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 ▼
$eqEqual to - matches values that are equal to specified value
{age: {$eq: 25}}$neNot equal to - matches values that are not equal
{status: {$ne: "inactive"}}$gtGreater than - matches values greater than specified value
{age: {$gt: 18}}$gteGreater than or equal to
{score: {$gte: 80}}$ltLess than - matches values less than specified value
{age: {$lt: 65}}$lteLess than or equal to
{price: {$lte: 100}}$inMatch any value in array
{status: {$in: ["active", "pending", "approved"]}}$ninNot match any value in array
{status: {$nin: ["deleted", "banned"]}}Query Operators - Logical ▼
$andJoin query clauses with logical AND
{$and: [{age: {$gt: 18}}, {status: "active"}]}$orJoin query clauses with logical OR
{$or: [{age: {$lt: 18}}, {age: {$gt: 65}}]}$notInverts the effect of query expression
{age: {$not: {$gt: 18}}}$norJoin query clauses with logical NOR (opposite of OR)
{$nor: [{status: "active"}, {age: {$lt: 18}}]}Query Operators - Element ▼
$existsMatch documents that have the specified field
{email: {$exists: true}}$typeMatch documents where field is of specified BSON type
{age: {$type: "number"}}Query Operators - Evaluation ▼
$regexMatch documents using regular expressions
{name: {$regex: /^J/, $options: "i"}}$textPerform text search on indexed fields
{$text: {$search: "coffee shop"}}$whereMatch documents using JavaScript expression
{$where: "this.age > 18"}$exprUse aggregation expressions in queries
{$expr: {$gt: ["$spent", "$budget"]}}$modPerform modulo operation on field value
{qty: {$mod: [4, 0]}}Query Operators - Array ▼
$allMatch arrays containing all specified elements
{tags: {$all: ["red", "blue"]}}$elemMatchMatch array elements that satisfy all conditions
{results: {$elemMatch: {$gte: 80, $lt: 85}}}$sizeMatch arrays with specified size
{tags: {$size: 3}}Update Operators ▼
$setSet the value of a field in document
{$set: {age: 30, status: "active"}}$unsetRemove specified field from document
{$unset: {middleName: ""}}$incIncrement field value by specified amount
{$inc: {age: 1, views: 5}}$mulMultiply field value by specified number
{$mul: {price: 1.1}}$renameRename a field
{$rename: {"oldName": "newName"}}$minUpdate field only if specified value is less than current
{$min: {lowScore: 50}}$maxUpdate field only if specified value is greater than current
{$max: {highScore: 100}}$currentDateSet field to current date/timestamp
{$currentDate: {lastModified: true}}Array Update Operators ▼
$pushAdd element to array
{$push: {tags: "new-tag"}}$popRemove first (-1) or last (1) element from array
{$pop: {tags: 1}}$pullRemove all matching elements from array
{$pull: {tags: "old-tag"}}$addToSetAdd element to array only if it doesn't exist (unique)
{$addToSet: {tags: "unique-tag"}}$pullAllRemove all specified values from array
{$pullAll: {tags: ["tag1", "tag2", "tag3"]}}Aggregation Pipeline Stages ▼
$matchFilter documents (like WHERE in SQL)
db.orders.aggregate([
{$match: {status: "completed"}}
])$groupGroup documents by specified expression
db.orders.aggregate([
{$group: {_id: "$category", total: {$sum: "$amount"}}}
])$projectReshape documents (include/exclude fields)
{$project: {name: 1, age: 1, _id: 0}}$sortSort documents by specified fields
{$sort: {age: -1, name: 1}}$limitLimit number of documents in pipeline
{$limit: 10}$skipSkip specified number of documents
{$skip: 5}$unwindDeconstruct array field into separate documents
{$unwind: "$tags"}$lookupPerform left outer join with another collection
{$lookup: {
from: "orders",
localField: "_id",
foreignField: "userId",
as: "userOrders"
}}$outWrite aggregation results to new collection
{$out: "aggregated_results"}$countCount documents in pipeline
{$count: "totalDocuments"}Aggregation Accumulator Operators ▼
$sumCalculate sum of numeric values
{$group: {_id: "$category", total: {$sum: "$amount"}}}$avgCalculate average of numeric values
{$group: {_id: "$category", avgScore: {$avg: "$score"}}}$minGet minimum value from group
{$group: {_id: "$category", minPrice: {$min: "$price"}}}$maxGet maximum value from group
{$group: {_id: "$category", maxPrice: {$max: "$price"}}}$firstGet first value in group
{$group: {_id: "$category", firstName: {$first: "$name"}}}$lastGet last value in group
{$group: {_id: "$category", lastName: {$last: "$name"}}}$pushCreate array from all values in group
{$group: {_id: "$category", items: {$push: "$item"}}}$addToSetCreate 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 ▼
StringUTF-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}Double64-bit IEEE 754 floating point numbers
{price: 19.99, pi: 3.14159}BooleanTrue or false values
{isActive: true, verified: false}DateDate and time (stored as milliseconds since Unix epoch)
{createdAt: ISODate("2024-01-15T10:30:00Z")}NullNull value or nonexistent field
{middleName: null}ObjectEmbedded document (nested object)
{address: {street: "123 Main St", city: "NYC"}}ArrayOrdered list of values
{tags: ["mongodb", "database", "nosql"]}ObjectId12-byte unique document identifier (default _id type)
{_id: ObjectId("507f1f77bcf86cd799439011")}BinaryBinary data for storing files and byte arrays
{file: BinData(0, "base64encodeddata")}RegExpRegular expression patterns
{pattern: /^[A-Z]/i}TimestampInternal MongoDB timestamp (for replication/sharding)
{ts: Timestamp(1, 1)}Backup & Restore Commands ▼
mongodumpCreate binary backup of all databases
mongodump --db <dbname>Backup specific database
mongodump --db myDatabasemongodump --db <dbname> --collection <collname>Backup specific collection
mongodump --db myDatabase --collection usersmongodump --out /backup/pathSpecify custom backup directory
mongorestoreRestore all databases from backup
mongorestore --db <dbname> /path/to/backupRestore specific database
mongorestore --dropDrop existing collections before restoring
mongodump --archive | mongorestore --archivePipe 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
db.collection.find({}, {name: 1, email: 1, _id: 0})explain() to analyze query performance and optimize slow queriesmongodb://[username:password@]host[:port][/database]$lookup for joining collections (similar to SQL JOIN operations)📚 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.
