MongoDB Cheat Sheet
9 groups · 34 topics · Updated
MongoDB is a document database: instead of rows in tables it stores JSON-like documents in collections, and each document can have its own shape. The commands below are mongosh, the official shell, written for MongoDB 7 or later. For the table-shaped alternative, see the MySQL cheat sheet.
Getting started
Connecting, and the words for the things you are connecting to.
Connect
mongosh
mongosh "mongodb://localhost:27017/shop"
mongosh "mongodb+srv://user@cluster.net/"mongodb+srv://is the Atlas form: it finds the cluster's servers for you.- Keep the connection string in an environment variable, not in the code.
The words
| MongoDB | Roughly |
|---|---|
| Database | Database |
| Collection | Table |
| Document | Row |
| Field | Column |
| Index | Index |
$lookup |
Join |
| Aggregation pipeline | GROUP BY and more |
Look around
show dbs
use shop // created on first write
show collections
db.orders.countDocuments()
db.orders.findOne()
db.orders.getIndexes()
db.stats()- A database and a collection appear only when a document is first written.
A document
{
_id: ObjectId("6554..."),
sku: "abc",
price: 9.99,
tags: ["new", "sale"],
stock: { warehouse: 3, shop: 1 },
addedAt: ISODate("2026-11-19T10:00:00Z")
}- Every document has an
_id, unique in the collection, made for you if you omit it. - An
ObjectIdcarries its creation time:id.getTimestamp().
Reading documents
find and the operators that narrow it.
find
db.orders.find()
db.orders.find({ status: "paid" })
db.orders.findOne({ _id: 42 })
db.orders.find({}, { total: 1, _id: 0 })
db.orders.find().sort({ total: -1 })
.skip(40).limit(20)- The second argument is the projection:
1to keep a field,0to drop it. .pretty()is the default inmongosh; you no longer need it.
Comparison operators
| Operator | Matches |
|---|---|
$eq, $ne |
Equal, not equal |
$gt, $gte |
Greater than, or equal |
$lt, $lte |
Less than, or equal |
$in, $nin |
In, or not in, a list |
$exists |
The field is present |
$type |
The field's BSON type |
$regex |
A regular expression |
db.orders.find({
total: { $gte: 100, $lt: 500 },
status: { $in: ["new", "paid"] },
note: { $exists: false }
})Combining conditions
db.orders.find({
$or: [
{ status: "paid" },
{ total: { $gt: 500 } }
]
})
db.orders.find({
$and: [{ a: 1 }, { b: 2 }]
})
db.orders.find({ status: { $not: /^p/ } })- Fields listed side by side are already an implicit
$and.
Inside objects and arrays
db.p.find({ "stock.shop": { $gt: 0 } })
db.p.find({ tags: "sale" }) // any element
db.p.find({ tags: ["new", "sale"] }) // exact
db.p.find({ tags: { $all: ["new","sale"] } })
db.p.find({ tags: { $size: 2 } })
db.p.find({
items: { $elemMatch: { qty: { $gt: 2 },
sku: "abc" } }
})- Without
$elemMatch, two conditions on an array may be met by two different elements.
Counting and distinct
db.orders.countDocuments({ status: "paid" })
db.orders.estimatedDocumentCount() // fast
db.orders.distinct("status")estimatedDocumentCountreads metadata, so it ignores any filter and may lag.
Writing documents
Inserting, updating and deleting, with the update operators.
Insert
db.orders.insertOne({
customerId: 7, total: 99.5, status: "new"
})
db.orders.insertMany([
{ customerId: 7, total: 10 },
{ customerId: 8, total: 20 }
], { ordered: false })ordered: falsekeeps going after a failed document instead of stopping.
Update
db.orders.updateOne(
{ _id: 42 },
{ $set: { status: "paid" },
$inc: { version: 1 },
$currentDate: { paidAt: true } }
)
db.orders.updateMany(
{ status: "new" },
{ $set: { status: "paid" } }
)
db.orders.replaceOne({ _id: 42 },
{ total: 5 })- Forget
$setand you replace the whole document with the one you passed.
Update operators
| Operator | Does |
|---|---|
$set, $unset |
Set a field, remove a field |
$inc |
Add a number, negative to subtract |
$mul |
Multiply |
$min, $max |
Set only if lower, or higher |
$rename |
Rename a field |
$push, $pull |
Add to, remove from, an array |
$addToSet |
Push only if not already there |
$pop |
Remove first (-1) or last (1) |
$setOnInsert |
Only when an upsert inserts |
Upsert and return
db.stock.updateOne(
{ sku: "abc" },
{ $inc: { qty: 5 },
$setOnInsert: { addedAt: new Date() } },
{ upsert: true }
)
db.stock.findOneAndUpdate(
{ sku: "abc" },
{ $inc: { qty: -1 } },
{ returnDocument: "after" }
)Delete
db.orders.deleteOne({ _id: 42 })
db.orders.deleteMany({ status: "cancelled" })
db.orders.deleteMany({}) // empties it
db.orders.drop() // removes itdeleteMany({})with an empty filter removes every document. Count first.
Bulk writes
db.orders.bulkWrite([
{ insertOne: { document: { total: 1 } } },
{ updateOne: {
filter: { _id: 42 },
update: { $inc: { total: 1 } } } },
{ deleteOne: { filter: { _id: 7 } } }
])Indexes
How MongoDB avoids reading every document, and how to check that it did.
Create an index
db.orders.createIndex({ customerId: 1 })
db.orders.createIndex({ email: 1 },
{ unique: true })
db.orders.createIndex(
{ customerId: 1, createdAt: -1 })
db.orders.createIndex({ note: "text" })
db.orders.dropIndex("customerId_1")1is ascending,-1descending. It matters only for sorting and compound keys.
Kinds of index
| Kind | Use |
|---|---|
| Single field | One field in a filter |
| Compound | Several fields, left to right |
| Multikey | Automatic on an array field |
| Text | Word search in strings |
2dsphere |
Coordinates and $near |
| Partial | Only documents matching a filter |
| TTL | Deletes documents after a time |
| Vector | Semantic search on embeddings |
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 })- A vector index is an Atlas feature, searched with
$vectorSearchrather thanfind. See the RAG cheat sheet.
ESR: the order of a compound key
// query: { status: "paid",
// total: { $gt: 100 } }
// sort: { createdAt: -1 }
db.orders.createIndex({
status: 1, createdAt: -1, total: 1 })- Equality first, then Sort, then Range. A sort not covered by an index is done in memory and fails over 100 MB.
Read the plan
db.orders.find({ status: "paid" })
.explain("executionStats")stage |
Meaning |
|---|---|
IXSCAN |
An index was used: good |
COLLSCAN |
Every document was read |
FETCH |
Documents read after the index |
SORT |
Sorted in memory: add an index |
- Compare
totalDocsExaminedwithnReturned: close together is healthy.
Aggregation
A pipeline of stages, each taking the documents the last one produced.
The shape of a pipeline
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$customerId",
spent: { $sum: "$total" },
n: { $sum: 1 } } },
{ $sort: { spent: -1 } },
{ $limit: 10 }
])$matchfirst, before the data grows: it can use an index, later stages cannot.
Common stages
| Stage | Does |
|---|---|
$match |
Filters, like find |
$project |
Chooses and computes fields |
$group |
One document per key |
$sort, $limit, $skip |
As in find |
$unwind |
One document per array element |
$lookup |
Pulls in another collection |
$addFields, $set |
Adds a computed field |
$count |
Replaces all with a count |
$facet |
Several pipelines at once |
Accumulators
{ $group: {
_id: "$status",
total: { $sum: "$total" },
avg: { $avg: "$total" },
min: { $min: "$total" },
first: { $first: "$createdAt" },
skus: { $addToSet: "$sku" },
all: { $push: "$sku" }
} }_id: nullgroups everything into one document.
Join with $lookup
db.orders.aggregate([
{ $lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customer" } },
{ $unwind: "$customer" },
{ $project: { total: 1,
name: "$customer.name" } }
])asis always an array;$unwindflattens it to one document.
Computed fields
{ $project: {
gross: { $multiply: ["$total", 1.2] },
month: { $month: "$createdAt" },
big: { $cond: [{ $gt: ["$total", 500] },
"yes", "no"] },
name: { $ifNull: ["$name", "unknown"] }
} }- A field name is quoted with
$when you mean its value:"$total".
Transactions and safety
Multi-document writes, and the settings that decide when a write counts.
A transaction
const s = db.getMongo().startSession()
s.startTransaction()
try {
const d = s.getDatabase("shop")
d.accounts.updateOne({ _id: 1 },
{ $inc: { bal: -100 } }, { session: s })
d.accounts.updateOne({ _id: 2 },
{ $inc: { bal: 100 } }, { session: s })
s.commitTransaction()
} catch (e) {
s.abortTransaction()
}- Transactions need a replica set and cost more than a single write. A document holding what belongs together often removes the need for one.
Write and read concern
db.orders.insertOne(doc, { writeConcern:
{ w: "majority", j: true } })
db.orders.find().readConcern("majority")| Setting | Means |
|---|---|
w: 1 |
One server has it |
w: "majority" |
Most of the set has it |
j: true |
Written to the journal on disk |
readPreference |
Primary, or a secondary |
Schema validation
db.createCollection("orders", {
validator: { $jsonSchema: {
required: ["customerId", "total"],
properties: {
total: { bsonType: "double",
minimum: 0 } } } }
})- Flexible shape does not mean no shape: validation stops the typos.
Injection and access
// Bad: a user-supplied object can be
// { $ne: null } and match everything.
db.users.findOne({ email: req.body.email })
// Good: force it to a string.
db.users.findOne({
email: String(req.body.email) })- Validate types at the edge. See how to secure a website and OWASP's NoSQL injection guidance.
- Create a role-limited user per application; never ship with authentication off.
Design and tools
Shaping documents, and the commands around the database.
Embed or reference
| Embed when | Reference when |
|---|---|
| Read together | Read separately |
| Few, bounded children | Many, unbounded children |
| Children change with the parent | Children change alone |
| Under 16 MB in total | It would grow past 16 MB |
// Embedded: one read gets everything
{ _id: 1, name: "Ada",
addresses: [{ city: "Leeds" }] }
// Referenced: ids point elsewhere
{ _id: 1, name: "Ada", orderIds: [7, 8] }- Model for the queries you run, not for the tidiest diagram. See hash tables explained for why lookup by key is the cheap operation.
Useful patterns
| Pattern | Use |
|---|---|
| Bucket | Group time-series points per hour |
| Computed | Store the total you keep reading |
| Extended reference | Copy the few fields you join for |
| Subset | Keep the top 10, link the rest |
| Outlier | Handle the one huge document apart |
Backup and import
mongodump --uri="$URI" --out=dump/
mongorestore --uri="$URI" dump/
mongoexport --collection=orders \
--out=orders.json
mongoimport --collection=orders \
--file=orders.jsonmongodumpwrites BSON and round-trips exactly;mongoexportwrites JSON and loses some types.
Node.js driver
import { MongoClient } from "mongodb";
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);
const db = client.db("shop");
const orders = db.collection("orders");
await orders.insertOne({ total: 10 });
const list = await orders
.find({ status: "paid" })
.sort({ total: -1 })
.limit(20)
.toArray();- Create one
MongoClientfor the whole process: it pools connections for you. - The driver's methods take the same filters and operators as the shell. For the language itself, see the JavaScript cheat sheet.
Watch out
The slips that cost an afternoon.
Common mistakes
| Mistake | Fix |
|---|---|
Update without $set |
The document is replaced |
deleteMany({}) |
Count the filter first |
"42" will not match 42 |
Types are not coerced |
_id is an ObjectId |
new ObjectId(str) to look up |
| Two array conditions | $elemMatch |
| Sorting with no index | Fails over 100 MB |
$match late in a pipeline |
Put it first |
| Unbounded array in a document | 16 MB cap; reference instead |
| Query inside a loop | $in, or $lookup |
| Trusting a request body object | Cast to the type you expect |
| Open to the internet, no auth | Bind to localhost; add users |
More help
The official pages to check details against.
Official documentation
| Topic | Page |
|---|---|
| Manual | MongoDB Manual |
| CRUD | CRUD operations |
| Operators | Query and projection operators |
| Aggregation | Aggregation pipeline |
| Indexes | Indexes |
| Drivers | Node.js driver |