Section 14: Cheatsheets
π» MongoDB Commands Cheatsheet
Complete reference guide with live console examples - All CRUD, database, collection, and admin commands
Basic Commands
Essential MongoDB shell commands
show dbs / show databases
Database
List all databases with their sizes
mongosh
> show dbs
admin 40.00 KiB
config 72.00 KiB
local 80.00 KiB
myDatabase 8.45 MiB
test 12.31 MiB
use <database>
Database
Switch to a database (creates if doesn't exist)
mongosh
> use myDatabase
switched to db myDatabase
> // Check current database
> db
myDatabase
show collections
Collection
List all collections in current database
mongosh
> show collections
users
products
orders
reviews
db.dropDatabase()
Dangerous
Delete entire database (β οΈ PERMANENT!)
mongosh
> // Drop entire database
> db.dropDatabase()
{ ok: 1, dropped: "myDatabase" }
> // Drop specific collection
> db.users.drop()
true
β οΈ Warning
These operations are PERMANENT and cannot be undone! Always backup before dropping databases or collections in production.
CRUD Operations
Create, Read, Update, Delete commands
insertOne() / insertMany()
Create
Insert single or multiple documents
mongosh
> // Insert single document
> db.users.insertOne({
name: "John Doe",
email: "john@example.com",
age: 25
})
{
acknowledged: true,
insertedId: ObjectId('674f3a1b2c3d4e5f67890abc')
}
> // Insert multiple documents
> db.users.insertMany([
{ name: "Alice", age: 30 },
{ name: "Bob", age: 28 }
])
{
acknowledged: true,
insertedIds: {
'0': ObjectId('674f3a1b2c3d4e5f67890abd'),
'1': ObjectId('674f3a1b2c3d4e5f67890abe')
}
}
find() / findOne()
Read
Retrieve documents from collection
mongosh
> // Find all documents
> db.users.find()
> // Find with filter
> db.users.find({ age: { $gte: 25 } })
> // Find one document
> db.users.findOne({ name: "John Doe" })
{
_id: ObjectId('674f3a1b2c3d4e5f67890abc'),
name: "John Doe",
email: "john@example.com",
age: 25
}
> // Find with projection (select fields)
> db.users.find(
{ age: { $gte: 25 } },
{ name: 1, age: 1, _id: 0 }
)
> // Pretty print
> db.users.find().pretty()
updateOne() / updateMany()
Update
Modify existing documents
mongosh
> // Update single document
> db.users.updateOne(
{ name: "John Doe" },
{ $set: { age: 26, city: "New York" } }
)
{
acknowledged: true,
matchedCount: 1,
modifiedCount: 1
}
> // Update multiple documents
> db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
)
> // Replace entire document
> db.users.replaceOne(
{ name: "John Doe" },
{ name: "John Smith", age: 27 }
)
deleteOne() / deleteMany()
Delete
Remove documents from collection
mongosh
> // Delete single document
> db.users.deleteOne({ name: "John Doe" })
{ acknowledged: true, deletedCount: 1 }
> // Delete multiple documents
> db.users.deleteMany({ age: { $lt: 18 } })
{ acknowledged: true, deletedCount: 5 }
> // Delete all documents in collection
> db.users.deleteMany({})
countDocuments()
Read
Count documents matching filter
mongosh
> // Count all documents
> db.users.countDocuments()
342
> // Count with filter
> db.users.countDocuments({ age: { $gte: 25 } })
187
Query Operators
Comparison and logical operators
| Operator | Description | Example |
|---|---|---|
$eq |
Equal to | { age: { $eq: 25 } } |
$ne |
Not equal to | { status: { $ne: "inactive" } } |
$gt |
Greater than | { price: { $gt: 100 } } |
$gte |
Greater than or equal | { age: { $gte: 18 } } |
$lt |
Less than | { score: { $lt: 50 } } |
$lte |
Less than or equal | { age: { $lte: 65 } } |
$in |
Match any in array | { status: { $in: ["active", "pending"] } } |
$nin |
Not in array | { role: { $nin: ["admin", "superuser"] } } |
$and |
Logical AND | { $and: [{ age: {$gte: 18} }, { age: {$lte: 65} }] } |
$or |
Logical OR | { $or: [{ status: "active" }, { vip: true }] } |
$not |
Logical NOT | { age: { $not: { $lt: 18 } } } |
$nor |
Logical NOR | { $nor: [{ status: "inactive" }, { deleted: true }] } |
$exists |
Field exists | { email: { $exists: true } } |
$type |
Field type check | { age: { $type: "number" } } |
$regex |
Pattern matching | { name: { $regex: /^John/i } } |
Query Operators in Action
> // Complex query with multiple operators
> db.users.find({
$and: [
{ age: { $gte: 18, $lte: 65 } },
{ status: { $in: ["active", "pending"] } },
{ email: { $exists: true } },
{ $or: [
{ vip: true },
{ purchases: { $gte: 10 } }
] }
]
})
> // Regex search (case-insensitive)
> db.users.find({
name: { $regex: /john/i }
})
Update Operators
Field and array update operators
| Operator | Description | Example |
|---|---|---|
$set |
Set field value | { $set: { age: 30 } } |
$unset |
Remove field | { $unset: { temporary: "" } } |
$inc |
Increment by value | { $inc: { views: 1 } } |
$mul |
Multiply by value | { $mul: { price: 1.1 } } |
$rename |
Rename field | { $rename: { "name": "fullName" } } |
$min |
Update if lower | { $min: { lowestScore: 75 } } |
$max |
Update if higher | { $max: { highScore: 1000 } } |
$currentDate |
Set to current date | { $currentDate: { lastModified: true } } |
$push |
Add to array | { $push: { tags: "mongodb" } } |
$pull |
Remove from array | { $pull: { tags: "old" } } |
$pop |
Remove first/last | { $pop: { items: 1 } } (1=last, -1=first) |
$addToSet |
Add if not exists | { $addToSet: { categories: "tech" } } |
Update Operators Examples
> // Increment views and update timestamp
> db.posts.updateOne(
{ _id: ObjectId("...") },
{
$inc: { views: 1 },
$currentDate: { lastViewed: true }
}
)
> // Add to array (with $each for multiple)
> db.posts.updateOne(
{ _id: ObjectId("...") },
{ $push: {
tags: { $each: ["mongodb", "database"] }
} }
)
> // Remove from array
> db.posts.updateOne(
{ _id: ObjectId("...") },
{ $pull: { tags: "old-tag" } }
)
Index Commands
Create and manage indexes
createIndex()
Index
Create an index on one or more fields
mongosh
> // Single field index
> db.users.createIndex({ email: 1 })
> // Compound index
> db.users.createIndex({ age: 1, city: 1 })
> // Unique index
> db.users.createIndex(
{ email: 1 },
{ unique: true }
)
> // Text index for search
> db.posts.createIndex({
title: "text",
content: "text"
})
> // TTL index (auto-delete after time)
> db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
getIndexes() / dropIndex()
Index
View and manage existing indexes
mongosh
> // List all indexes
> db.users.getIndexes()
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { email: 1 }, name: 'email_1', unique: true },
{ v: 2, key: { age: 1, city: 1 }, name: 'age_1_city_1' }
]
> // Drop specific index
> db.users.dropIndex("email_1")
> // Drop all indexes except _id
> db.users.dropIndexes()
Aggregation Commands
Data processing pipelines
aggregate()
Aggregation
Process data through aggregation pipeline
mongosh
> // Simple aggregation
> db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$customerId",
totalSpent: { $sum: "$amount" },
orderCount: { $sum: 1 }
} },
{ $sort: { totalSpent: -1 } },
{ $limit: 10 }
])
> // Complex pipeline with $lookup
> db.orders.aggregate([
{ $lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerInfo"
} },
{ $unwind: "$customerInfo" },
{ $project: {
orderTotal: 1,
customerName: "$customerInfo.name"
} }
])
π‘ Common Pipeline Stages
$match- Filter documents$group- Group and aggregate$project- Reshape documents$sort- Sort results$limit- Limit results$skip- Skip documents$unwind- Deconstruct arrays$lookup- Join collections
Admin Commands
Database administration
db.stats()
Info
Get database statistics
mongosh
> db.stats()
{
db: 'myDatabase',
collections: 5,
views: 0,
objects: 10523,
avgObjSize: 347.2,
dataSize: 3652438,
storageSize: 1368064,
indexes: 8,
indexSize: 286720
}
> // Collection stats
> db.users.stats()
explain()
Performance
Analyze query performance
mongosh
> // Query plan
> db.users.find({ age: { $gte: 25 } }).explain()
> // Execution stats
> db.users.find({ age: { $gte: 25 } })
.explain("executionStats")
{
executionStats: {
executionTimeMillis: 2,
totalKeysExamined: 187,
totalDocsExamined: 187,
nReturned: 187,
executionStages: {
stage: 'IXSCAN', // Using index!
indexName: 'age_1'
}
}
}
| Command | Description |
|---|---|
db.serverStatus() |
Server status and metrics |
db.currentOp() |
Current running operations |
db.killOp(opid) |
Kill a running operation |
db.getCollectionNames() |
List all collection names |
db.version() |
MongoDB version |
db.hostInfo() |
Host system information |
Import/Export Commands
Data backup and migration
mongoimport / mongoexport
Shell
Import/Export JSON or CSV data (run in system shell, not mongosh)
bash / cmd
$ # Export collection to JSON
$ mongoexport --db=myDatabase --collection=users --out=users.json
$ # Export with query filter
$ mongoexport --db=myDatabase --collection=users --query='{"age": {"$gte": 25}}' --out=adult-users.json
$ # Import JSON data
$ mongoimport --db=myDatabase --collection=users --file=users.json
$ # Import CSV with field names
$ mongoimport --db=myDatabase --collection=users --type=csv --headerline --file=users.csv
mongodump / mongorestore
Backup
Full database backup and restore (BSON format)
bash / cmd
$ # Backup entire database
$ mongodump --db=myDatabase --out=/backup/
$ # Backup specific collection
$ mongodump --db=myDatabase --collection=users --out=/backup/
$ # Restore database
$ mongorestore --db=myDatabase /backup/myDatabase/
$ # Restore specific collection
$ mongorestore --db=myDatabase --collection=users /backup/myDatabase/users.bson
β οΈ Important Notes
mongoexport/mongoimport- JSON/CSV format, human-readablemongodump/mongorestore- BSON format, preserves all data types- For production backups, always use
mongodump - Always test restore on non-production environment first
π‘ Quick Command Reference
// Connection
mongosh // Connect to local MongoDB
mongosh "mongodb://host:port/db" // Connect to remote
// Help
help // Show help
db.help() // Database methods
db.collection.help() // Collection methods
// Quick Stats
db.stats() // Database stats
db.collection.stats() // Collection stats
db.collection.countDocuments() // Count documents
// Performance
db.collection.find().explain() // Query plan
db.collection.getIndexes() // List indexes