MongoDB cheat sheet
A scannable MongoDB reference: 18 short snippets across 12 topics, each linking back to the lesson it came from.
At a glance
| Topic | What it covers | |
|---|---|---|
| The aggregation pipeline | A pipeline is an array of stages; each takes the documents produced by the previous stage and emits new ones. Read it | lesson |
| Indexes and schema design patterns | A compound index is a sorted structure over several fields in a fixed order, and like any B-tree it is usable only from | lesson |
| Setting up MongoDB: Atlas, local install and mongosh | Choose between a local server, a container and Atlas, connect with mongosh, and get data in and out with CRUD, bulk | lesson |
| Data modelling: embedding vs referencing and schema validation | Decide when a child belongs inside the parent document, enforce the shape you settled on with JSON Schema, and evolve | lesson |
| Transactions, sessions and read/write concerns | A session is the context for a sequence of operations. It carries an operation time and a cluster time, which is what | lesson |
| Drivers and ODMs in application code | Wire the official driver correctly with a single client per process, know what an ODM adds and hides, and handle the | lesson |
| Security: authentication, roles and encryption | Turn on authentication before anything else, grant the narrowest role that works, encrypt the wire and the sensitive | lesson |
| Performance tuning with explain() and the profiler | The three verbs are cumulative: queryPlanner shows the chosen plan, executionStats runs it and reports counts, and | lesson |
| Replica sets, failover and read preferences | Run a set with a real majority, understand what an election costs and what a write concern protects, and route reads to | lesson |
| Sharding and horizontal scaling | Understand routers, config servers and chunks, choose a shard key that keeps queries targeted and writes even, and know | lesson |
| Backup, restore and operational tooling | Pick a backup method from your recovery target rather than from convenience, restore into a scratch namespace first | lesson |
| Next steps: Atlas Search, time series and vector search | Add full-text relevance and vector similarity as pipeline stages, store measurements in time-series collections instead | lesson |
Quick snippets
The aggregation pipeline
Keeping a pipeline fast
db.orders.explain("executionStats").aggregate([
{ $match: { status: "paid", placedAt: { $gte: ISODate("2026-01-01") } } },
{ $group: { _id: "$customer.id", total: { $sum: 1 } } }
]);Full lesson: The aggregation pipeline →
Indexes and schema design patterns
Schema patterns
// bucket pattern: one document per hour instead of one per reading
db.readings.updateOne(
{ sensorId: "s-12", hour: ISODate("2026-09-18T09:00:00Z") },
{
$push: { values: { t: new Date(), v: 21.4 } },
$inc: { count: 1, sum: 21.4 },
$min: { minV: 21.4 },
$max: { maxV: 21.4 },
$setOnInsert: { sensorId: "s-12", hour: ISODate("2026-09-18T09:00:00Z") }
},
{ upsert: true }
);Full lesson: Indexes and schema design patterns →
Setting up MongoDB: Atlas, local install and mongosh
Bulk writes and importing data
mongoimport --uri "mongodb://localhost:27017/shop" \
--collection customers --file customers.json --jsonArray
mongoexport --uri "mongodb://localhost:27017/shop" \
--collection orders --out orders.json
# run a script that seeds a development database
mongosh "mongodb://localhost:27017/shop" --file seed.js
# check without opening the shell
mongosh "mongodb://localhost:27017/shop" --eval 'db.orders.countDocuments()'Full lesson: Setting up MongoDB: Atlas, local install and mongosh →
Data modelling: embedding vs referencing and schema validation
Evolving a schema safely
// version the shape, then migrate lazily in batches
db.orders.updateMany(
{ schemaVersion: { $lt: 2 } },
{ $set: { schemaVersion: 2, "shipping.method": "standard" } }
);
db.orders.createIndex({ schemaVersion: 1 });
db.orders.countDocuments({ schemaVersion: { $lt: 2 } }); // backlog remainingFull lesson: Data modelling: embedding vs referencing and schema validation →
Transactions, sessions and read/write concerns
Sessions and causal consistency
const session = db.getMongo().startSession();
const s = session.getDatabase("shop");
s.orders.insertOne({ customer: "Ada", status: "new" });
s.orders.findOne({ customer: "Ada" }); // sees the insert above
session.endSession();
// causal consistency is on by default; this makes it explicit
const causal = db.getMongo().startSession({ causalConsistency: true });Full lesson: Transactions, sessions and read/write concerns →
Drivers and ODMs in application code
ODMs and schema layers
const orderSchema = new Schema({
customer: { type: Schema.Types.ObjectId, ref: "Customer", required: true },
status: { type: String, enum: ["new", "paid", "shipped"], default: "new" },
total: { type: Schema.Types.Decimal128, min: 0 },
placedAt: { type: Date, default: Date.now },
}, { timestamps: true, strict: "throw" });
orderSchema.index({ customer: 1, placedAt: -1 });
const Order = model("Order", orderSchema);
const doc = await Order.findById(id).lean(); // plain object, not hydratedFull lesson: Drivers and ODMs in application code →
Security: authentication, roles and encryption
Authentication
# start with authentication and TLS enforced
mongod --auth --tlsMode requireTLS \
--tlsCertificateKeyFile /etc/ssl/mongo.pem \
--bind_ip 10.0.0.11
mongosh "mongodb://localhost:27017/?authSource=admin"Full lesson: Security: authentication, roles and encryption →
Performance tuning with explain() and the profiler
explain() verbosity and reading a plan
db.orders.find({
status: "paid",
placedAt: { $gte: ISODate("2026-01-01") }
}).explain("executionStats");
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$customer.id", n: { $sum: 1 } } }
]).explain("queryPlanner");
The profiler and index statistics
db.setProfilingLevel(1, { slowms: 100 }); // 0 off, 1 slow, 2 everything
db.system.profile.find({ millis: { $gt: 100 } })
.sort({ ts: -1 }).limit(5);
db.system.profile.find({ planSummary: "COLLSCAN" }).count();
db.orders.aggregate([{ $indexStats: {} }]); // uses per index since restart
db.orders.stats().indexSizes;Full lesson: Performance tuning with explain() and the profiler →
Replica sets, failover and read preferences
A replica set
mongod --replSet rs0 --dbpath /data/rs0 --port 27017 --bind_ip localhost
mongod --replSet rs0 --dbpath /data/rs1 --port 27018 --bind_ip localhost
mongod --replSet rs0 --dbpath /data/rs2 --port 27019 --bind_ip localhost
mongosh --port 27017
A replica set
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "127.0.0.1:27017", priority: 2 },
{ _id: 1, host: "127.0.0.1:27018" },
{ _id: 2, host: "127.0.0.1:27019" }
]
});
rs.status();
rs.conf();
db.hello();
Elections and write concern
db.adminCommand({ replSetGetStatus: 1 })
.members.forEach(m => print(m.name, m.stateStr));
db.getSiblingDB("local").oplog.rs.stats().maxSize;
rs.printReplicationInfo(); // oldest oplog entry, and the window it covers
rs.stepDown(60); // deliberately hand over the primary roleFull lesson: Replica sets, failover and read preferences →
Sharding and horizontal scaling
How a sharded cluster is put together
sh.enableSharding("shop");
sh.shardCollection("shop.orders", { customerId: "hashed" });
sh.shardCollection("shop.events", { tenantId: 1, createdAt: 1 });
sh.status();
sh.getBalancerState();
db.orders.getShardDistribution();
Choosing a shard key
// targeted: the filter contains the shard key
db.orders.find({ customerId: "c-42", placedAt: { $gte: ISODate("2026-01-01") } })
// scatter-gather: no shard key, so every shard is asked
db.orders.find({ status: "paid" })
Scaling without surprises
sh.moveChunk("shop.orders", { customerId: "c-9999" }, "shard02");
sh.splitAt("shop.orders", { customerId: "c-5000" });
sh.balancerStop();
sh.balancerStart();Full lesson: Sharding and horizontal scaling →
Backup, restore and operational tooling
The backup methods
mongodump --uri "mongodb+srv://user:[email protected]/shop" \
--out /backups/2026-09-18 --gzip --oplog
mongorestore --uri "mongodb://localhost:27017" \
--gzip --oplogReplay --drop /backups/2026-09-18
# single-archive form, easier to move and encrypt
mongodump --uri "$URI" --archive=shop.archive --gzip
Restoring without surprises
db.orders.countDocuments({})
db.orders.aggregate([
{ $group: { _id: null, total: { $sum: "$total" }, orders: { $sum: 1 } } }
])Full lesson: Backup, restore and operational tooling →
Next steps: Atlas Search, time series and vector search
Vector search, and when to choose another store
db.products.aggregate([
{ $vectorSearch: {
index: "vector_index",
path: "embedding",
queryVector: queryVec, // same model and dimension as the index
numCandidates: 200,
limit: 10
} },
{ $project: { title: 1, score: { $meta: "vectorSearchScore" } } }
])Full lesson: Next steps: Atlas Search, time series and vector search →
FAQ
Is this MongoDB cheat sheet free to use?
Where do the examples come from?
How do I go deeper than a cheat sheet?
Related cheat sheets
SQL MySQL PostgreSQL Redis SQLite
Last refreshed 2026-09-27.