MongoDB Cheatsheet
Getting Started
Installation
wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
brew tap mongodb/brew
brew install mongodb-community
sudo systemctl start mongod
brew services start mongodb-community
mongo
mongosh
sudo systemctl status mongod
brew services list | grep mongodb
MongoDB Shell Commands
use myDatabase
show dbs
show collections
db
db.users.stats()
db.stats()
help
db.help()
db.users.help()
exit
quit()
Connection URI
mongodb://localhost:27017/mydatabase
mongodb://username:password@localhost:27017/mydatabase
mongodb://host1:27017,host2:27017,host3:27017/mydatabase?replicaSet=myReplSet
mongodb://username:password@host:27017/mydatabase?authSource=admin&ssl=true
export MONGODB_URI="mongodb://username:password@localhost:27017/mydatabase"
Database Operations
Create and Drop Database
use company_db
db.dropDatabase()
show dbs
db.stats()
db.createCollection("employees")
db.createCollection("products", {
capped: true,
size: 100000,
max: 5000
})
db.employees.drop()
Users and Authentication
use admin
db.createUser({
user: "admin",
pwd: "password123",
roles: ["userAdminAnyDatabase", "readWriteAnyDatabase"]
})
use company_db
db.createUser({
user: "appuser",
pwd: "apppass123",
roles: ["readWrite"]
})
db.createUser({
user: "readonly",
pwd: "readonly123",
roles: ["read"]
})
db.updateUser("appuser", {
pwd: "newpassword123",
roles: ["readWrite", "dbAdmin"]
})
db.getUsers()
db.dropUser("username")
db.auth("username", "password")
db.changeUserPassword("username", "newpassword")
db.grantRolesToUser("username", ["readWrite"])
db.revokeRolesFromUser("username", ["dbAdmin"])
Document Operations (CRUD)
Insert Documents
db.users.insertOne({
name: "John Doe",
email: "john@example.com",
age: 30,
active: true,
tags: ["developer", "mongodb"],
address: {
street: "123 Main St",
city: "New York",
zipcode: "10001"
},
createdAt: new Date()
})
db.users.insertMany([
{
name: "Jane Smith",
email: "jane@example.com",
age: 25,
active: true,
tags: ["designer", "ui/ux"]
},
{
name: "Bob Johnson",
email: "bob@example.com",
age: 35,
active: false,
tags: ["manager", "sales"]
}
])
db.users.insertMany([
{ name: "User1", email: "user1@example.com" },
{ name: "User2", email: "user2@example.com" }
], { ordered: false })
db.users.insertOne(
{ name: "Critical User", email: "critical@example.com" },
{ writeConcern: { w: "majority", j: true } }
)
Find Documents
db.users.find()
db.users.find().pretty()
db.users.findOne()
db.users.find({ age: 30 })
db.users.find({ active: true })
db.users.find({ "address.city": "New York" })
db.users.find({ age: 30, active: true })
db.users.find({
$or: [
{ age: { $lt: 25 } },
{ age: { $gt: 35 } }
]
})
db.users.find({ age: { $gt: 25 } })
db.users.find({ age: { $gte: 25 } })
db.users.find({ age: { $lt: 35 } })
db.users.find({ age: { $lte: 35 } })
db.users.find({ age: { $ne: 30 } })
db.users.find({ age: { $in: [25, 30, 35] } })
db.users.find({ age: { $nin: [25, 30] } })
db.users.find({ tags: "developer" })
db.users.find({ tags: { $all: ["developer", "mongodb"] } })
db.users.find({ tags: { $size: 2 } })
db.users.find({ name: /^John/ })
db.users.find({ email: /@gmail\.com$/ })
db.users.find({ name: { $regex: "john", $options: "i" } })
db.users.find({ phone: { $exists: true } })
db.users.find({ phone: { $exists: false } })
db.users.find({ age: { $type: "number" } })
db.users.find({ age: { $type: 16 } })
db.users.find({}, { name: 1, email: 1 })
db.users.find({}, { _id: 0, name: 1 })
db.users.find({}, { tags: 0 })
db.users.find().limit(5)
db.users.find().skip(10).limit(5)
db.users.find().sort({ age: 1 })
db.users.find().sort({ age: -1 })
db.users.find().sort({ age: -1, name: 1 })
db.users.countDocuments()
db.users.countDocuments({ active: true })
db.users.distinct("age")
db.users.distinct("tags")
Update Documents
db.users.updateOne(
{ name: "John Doe" },
{ $set: { age: 31, lastUpdated: new Date() } }
)
db.users.updateMany(
{ active: false },
{ $set: { status: "inactive" } }
)
db.users.replaceOne(
{ name: "John Doe" },
{
name: "John Doe",
email: "john.doe@newcompany.com",
age: 31,
active: true
}
)
db.users.updateOne(
{ _id: ObjectId("...") },
{ $set: { "address.city": "San Francisco" } }
)
db.users.updateOne(
{ name: "John Doe" },
{ $unset: { temporaryField: "" } }
)
db.users.updateOne(
{ name: "John Doe" },
{ $inc: { age: 1, loginCount: 1 } }
)
db.users.updateOne(
{ name: "John Doe" },
{ $mul: { score: 1.1 } }
)
db.users.updateOne(
{ name: "John Doe" },
{ $min: { lowestScore: 85 } }
)
db.users.updateOne(
{ name: "John Doe" },
{ $max: { highestScore: 95 } }
)
db.users.updateOne(
{ name: "John Doe" },
{ $push: { tags: "expert" } }
)
db.users.updateOne(
{ name: "John Doe" },
{ $push: { tags: { $each: ["senior", "lead"] } } }
)
db.users.updateOne(
{ name: "John Doe" },
{ $pull: { tags: "beginner" } }
)
db.users.updateOne(
{ name: "John Doe" },
{ $pop: { tags: 1 } }
)
db.users.updateOne(
{ name: "John Doe" },
{ $addToSet: { tags: "mongodb" } }
)
db.users.updateOne(
{ email: "new@example.com" },
{ $set: { name: "New User", active: true } },
{ upsert: true }
)
db.users.updateOne(
{ "scores.subject": "math" },
{ $set: { "scores.$.score": 95 } }
)
db.users.updateMany(
{},
{ $set: { "scores.$[].passed": true } }
)
db.users.updateMany(
{},
{ $set: { "scores.$[elem].grade": "A" } },
{ arrayFilters: [{ "elem.score": { $gte: 90 } }] }
)
db.users.findOneAndUpdate(
{ name: "John Doe" },
{ $inc: { version: 1 } },
{ returnDocument: "after" }
)
Delete Documents
db.users.deleteOne({ name: "John Doe" })
db.users.deleteMany({ active: false })
db.users.deleteMany({})
const deletedUser = db.users.findOneAndDelete({ name: "John Doe" })
db.users.deleteOne(
{ name: "John Doe" },
{ writeConcern: { w: "majority" } }
)
Aggregation Pipeline
Basic Aggregation
db.users.aggregate([
{ $match: { active: true } },
{ $group: { _id: "$age", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])
db.users.aggregate([
{ $match: { age: { $gte: 18 } } }
])
db.users.aggregate([
{
$project: {
name: 1,
email: 1,
ageGroup: {
$cond: {
if: { $gte: ["$age", 18] },
then: "adult",
else: "minor"
}
}
}
}
])
db.sales.aggregate([
{
$group: {
_id: "$category",
totalSales: { $sum: "$amount" },
avgSale: { $avg: "$amount" },
maxSale: { $max: "$amount" },
minSale: { $min: "$amount" },
count: { $sum: 1 }
}
}
])
db.users.aggregate([
{ $sort: { age: -1, name: 1 } }
])
db.users.aggregate([
{ $skip: 10 },
{ $limit: 5 }
])
db.posts.aggregate([
{ $unwind: "$tags" },
{ $group: { _id: "$tags", count: { $sum: 1 } } }
])
Advanced Aggregation
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customer"
}
},
{ $unwind: "$customer" },
{
$project: {
orderDate: 1,
amount: 1,
customerName: "$customer.name"
}
}
])
db.users.aggregate([
{
$addFields: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
isAdult: { $gte: ["$age", 18] }
}
}
])
db.products.aggregate([
{
$facet: {
"byCategory": [
{ $group: { _id: "$category", count: { $sum: 1 } } }
],
"priceRanges": [
{
$bucket: {
groupBy: "$price",
boundaries: [0, 100, 500, 1000, Infinity],
default: "Other"
}
}
]
}
}
])
db.products.aggregate([
{
$bucket: {
groupBy: "$price",
boundaries: [0, 100, 500, 1000],
default: "Expensive",
output: {
count: { $sum: 1 },
avgPrice: { $avg: "$price" }
}
}
}
])
db.users.aggregate([
{ $sample: { size: 10 } }
])
db.articles.aggregate([
{ $match: { $text: { $search: "mongodb aggregation" } } },
{ $sort: { score: { $meta: "textScore" } } }
])
db.employees.aggregate([
{
$graphLookup: {
from: "employees",
startWith: "$managerId",
connectFromField: "managerId",
connectToField: "_id",
as: "managementHierarchy"
}
}
])
db.sales.aggregate([
{
$group: {
_id: {
year: { $year: "$date" },
month: { $month: "$date" }
},
totalSales: { $sum: "$amount" }
}
},
{ $sort: { "_id.year": 1, "_id.month": 1 } }
])
db.orders.aggregate([
{
$match: {
orderDate: { $gte: new Date(Date.now() - 30*24*60*60*1000) }
}
},
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customer"
}
},
{ $unwind: "$customer" },
{
$lookup: {
from: "products",
localField: "productId",
foreignField: "_id",
as: "product"
}
},
{ $unwind: "$product" },
{
$group: {
_id: {
customerId: "$customerId",
customerName: "$customer.name",
category: "$product.category"
},
totalSpent: { $sum: { $multiply: ["$quantity", "$product.price"] } },
orderCount: { $sum: 1 }
}
},
{
$addFields: {
loyaltyScore: {
$add: [
{ $multiply: ["$totalSpent", 0.1] },
{ $multiply: ["$orderCount", 10] }
]
}
}
},
{ $sort: { loyaltyScore: -1 } },
{ $limit: 100 }
])
Indexing
Create Indexes
db.users.createIndex({ email: 1 })
db.users.createIndex({ age: -1 })
db.users.createIndex({ age: 1, name: 1 })
db.posts.createIndex({ tags: 1 })
db.articles.createIndex({ title: "text", content: "text" })
db.locations.createIndex({ coordinates: "2dsphere" })
db.users.createIndex({ phone: 1 }, { sparse: true })
db.users.createIndex({ email: 1 }, { unique: true })
db.users.createIndex(
{ age: 1 },
{ partialFilterExpression: { age: { $gte: 18 } } }
)
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
db.users.createIndex({ name: 1 }, { background: true })
db.users.createIndex({ email: 1 }, { name: "unique_email_idx" })
Index Management
db.users.getIndexes()
db.users.aggregate([{ $indexStats: {} }])
db.users.dropIndex({ email: 1 })
db.users.dropIndex("unique_email_idx")
db.users.dropIndexes()
db.users.reIndex()
db.users.hideIndex("index_name")
db.users.unhideIndex("index_name")
db.users.find({ email: "john@example.com" }).explain("executionStats")
Schema Design and Validation
Schema Validation
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email", "age"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
email: {
bsonType: "string",
pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
description: "must be a valid email address"
},
age: {
bsonType: "int",
minimum: 0,
maximum: 120,
description: "must be an integer between 0 and 120"
},
status: {
enum: ["active", "inactive", "pending"],
description: "can only be one of the enum values"
}
}
}
},
validationLevel: "strict",
validationAction: "error"
})
db.runCommand({
collMod: "products",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price"],
properties: {
name: { bsonType: "string" },
price: { bsonType: "number", minimum: 0 },
category: { enum: ["electronics", "books", "clothing"] }
}
}
}
})
db.runCommand({
collMod: "users",
validator: {},
validationLevel: "off"
})
Design Patterns
{
_id: ObjectId("..."),
name: "John Doe",
email: "john@example.com",
addresses: [
{
type: "home",
street: "123 Main St",
city: "New York",
zipcode: "10001"
},
{
type: "work",
street: "456 Business Ave",
city: "New York",
zipcode: "10002"
}
]
}
{
_id: ObjectId("..."),
title: "MongoDB Tutorial",
content: "Learn MongoDB...",
author: "John Doe",
createdAt: new Date()
}
{
_id: ObjectId("..."),
postId: ObjectId("..."),
author: "Jane Smith",
content: "Great tutorial!",
createdAt: new Date()
}
{
_id: ObjectId("..."),
title: "Popular Post",
content: "This post has many comments...",
recentComments: [
{ author: "User1", content: "Comment 1", createdAt: new Date() },
{ author: "User2", content: "Comment 2", createdAt: new Date() }
],
totalComments: 50000,
commentPages: ["page1_id", "page2_id", "page3_id"]
}
{
_id: ObjectId("..."),
orderNumber: "ORD-12345",
customer: {
_id: ObjectId("..."),
name: "John Doe",
email: "john@example.com"
},
items: [...],
total: 150.00,
orderDate: new Date()
}
{
_id: ObjectId("..."),
sensorId: "sensor_001",
date: ISODate("2023-01-01T10:00:00Z"),
readings: [
{ time: ISODate("2023-01-01T10:00:00Z"), value: 23.5 },
{ time: ISODate("2023-01-01T10:01:00Z"), value: 23.7 },
],
count: 60,
sum: 1420.5,
avg: 23.675
}
Replica Sets and Sharding
Replica Set Operations
rs.initiate({
_id: "myReplicaSet",
members: [
{ _id: 0, host: "localhost:27017" },
{ _id: 1, host: "localhost:27018" },
{ _id: 2, host: "localhost:27019" }
]
})
rs.status()
rs.add("localhost:27020")
rs.remove("localhost:27020")
rs.stepDown()
db.isMaster()
db.users.find().readPref("secondary")
db.users.find().readPref("primaryPreferred")
db.users.insertOne(
{ name: "John" },
{ writeConcern: { w: "majority", j: true } }
)
Sharding
sh.enableSharding("myDatabase")
sh.shardCollection("myDatabase.users", { userId: 1 })
sh.shardCollection("myDatabase.orders", { customerId: 1, orderDate: 1 })
sh.status()
db.users.getShardDistribution()
sh.splitAt("myDatabase.users", { userId: 1000 })
sh.moveChunk("myDatabase.users", { userId: 1000 }, "shard0001")
sh.addShard("localhost:27020")
sh.removeShard("shard0001")
Performance and Monitoring
Performance Analysis
db.users.find({ age: { $gt: 25 } }).explain("executionStats")
db.setProfilingLevel(2)
db.setProfilingLevel(1, { slowms: 100 })
db.setProfilingLevel(0)
db.system.profile.find().limit(5).sort({ ts: -1 }).pretty()
db.currentOp()
db.killOp(opId)
db.stats()
db.users.stats()
db.users.aggregate([{ $indexStats: {} }])
db.serverStatus()
db.serverStatus().locks
db.serverStatus().mem
db.serverStatus().connections
Optimization Tips
db.users.find({}, { name: 1, email: 1 })
db.users.find({ age: 30 }, { age: 1, _id: 0 })
db.users.find({ name: "John" }).hint({ name: 1 })
db.users.aggregate([
{ $group: { _id: "$age", count: { $sum: 1 } } }
], { allowDiskUse: true })
const bulk = db.users.initializeUnorderedBulkOp()
for (let i = 0; i < 1000; i++) {
bulk.insert({ name: `User${i}`, age: Math.floor(Math.random() * 100) })
}
bulk.execute()
Security
Authentication and Authorization
use admin
db.createUser({
user: "admin",
pwd: "securePassword123",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})
use myapp
db.createUser({
user: "appUser",
pwd: "appPassword123",
roles: [
{ role: "readWrite", db: "myapp" }
]
})
use admin
db.createRole({
role: "customRole",
privileges: [
{
resource: { db: "myapp", collection: "users" },
actions: ["find", "insert", "update"]
}
],
roles: []
})
Auditing
Backup and Recovery
mongodump and mongorestore
mongodump --host localhost:27017 --db myDatabase --out /backup/
mongodump --host localhost:27017 --username admin --password --authenticationDatabase admin --db myDatabase --out /backup/
mongodump --host localhost:27017 --db myDatabase --collection users --out /backup/
mongodump --host localhost:27017 --db myDatabase --collection users --query '{"active": true}' --out /backup/
mongodump --host localhost:27017 --db myDatabase --gzip --out /backup/
mongorestore --host localhost:27017 --db myDatabase /backup/myDatabase/
mongorestore --host localhost:27017 --db newDatabase /backup/myDatabase/
mongorestore --host localhost:27017 --db myDatabase --collection users /backup/myDatabase/users.bson
mongorestore --host localhost:27017 --db myDatabase --drop /backup/myDatabase/
mongoexport and mongoimport
mongoexport --host localhost:27017 --db myDatabase --collection users --out users.json
mongoexport --host localhost:27017 --db myDatabase --collection users --type csv --fields name,email,age --out users.csv
mongoexport --host localhost:27017 --db myDatabase --collection users --query '{"active": true}' --out active_users.json
mongoimport --host localhost:27017 --db myDatabase --collection users --file users.json
mongoimport --host localhost:27017 --db myDatabase --collection users --type csv --headerline --file users.csv
mongoimport --host localhost:27017 --db myDatabase --collection users --upsert --file users.json
Replica Set Backup
mongodump --host secondary.example.com:27017 --db myDatabase --out /backup/
mongodump --host localhost:27017 --oplog --out /backup/
mongorestore --host localhost:27017 --oplogReplay /backup/
Best Practices
Performance Best Practices
- Create appropriate indexes for your query patterns
- Use projection to limit returned fields
- Limit result sets with limit() and skip()
- Use aggregation pipeline instead of client-side processing
- Avoid large documents (16MB limit)
- Use connection pooling in applications
- Monitor slow queries with profiler
- Use covered queries when possible
- Batch operations for bulk inserts/updates
- Consider read preferences for replica sets
Schema Design Best Practices
- Embed vs Reference based on access patterns
- Denormalize for read performance when appropriate
- Use atomic operations for data consistency
- Design for your queries not normalized structure
- Avoid unbounded arrays that grow indefinitely
- Use schema validation for data quality
- Consider document growth in design
- Use appropriate data types for efficiency
- Plan for scalability from the beginning
- Document your schema decisions
Security Best Practices
- Enable authentication and authorization
- Use strong passwords and regular rotation
- Implement SSL/TLS for network encryption
- Regular security updates for MongoDB
- Audit database access and operations
- Network security with firewalls
- Backup encryption for sensitive data
- Principle of least privilege for users
- Regular security assessments
- Monitor for suspicious activity