MongoDB Cheat Sheet
mongosh basics, insert, find, query operators, projection, sorting, updates, arrays, indexes, aggregation, $lookup, validation, text search, transactions, Node.js and operations on one printable page.
Basics
| Syntax | What it does | Lesson |
|---|---|---|
use shop show dbs show collections | Switch and list databases and collections | Introduction |
db.c.insertOne({ ... }) db.c.insertMany([...]) | Insert documents | Insert |
db.c.find({ status: 'paid' }) db.c.findOne({ _id }) | Find documents | Find & Queries |
{ 'address.city': 'Leeds' } { tags: 'gift' } | Nested fields and array contains | Find & Queries |
db.c.countDocuments(f) db.c.distinct('field') | Count and list unique values | Find & Queries |
Decimal128('19.99') ISODate('2026-03-01') { $type: 'string' } | Types | Data Types |
Queries & results
| Syntax | What it does | Lesson |
|---|---|---|
{ price: { $gte: 10, $lte: 50 } } | Range | Query Operators |
{ status: { $in: ['a', 'b'] } } { $or: [ ... ] } | Lists and alternatives | Query Operators |
{ phone: { $exists: false } } { name: { $regex: '^a', $options: 'i' } } | Presence and patterns | Query Operators |
{ items: { $elemMatch: { sku: 'X', qty: { $gt: 1 } } } } | One array element meets several conditions | Query Operators |
find(f, { name: 1, _id: 0 }) | Projection | Projection & Sorting |
.sort({ price: -1, _id: 1 }).skip(20).limit(20) | Sort and page | Projection & Sorting |
Writes
| Syntax | What it does | Lesson |
|---|---|---|
updateOne(f, { $set: { a: 1 }, $inc: { n: 1 } }) | Update fields | Update |
updateOne(f, u, { upsert: true }) $setOnInsert | Insert if missing | Update |
findOneAndUpdate(f, u, { returnDocument: 'after' }) | Update and return | Update |
deleteOne(f) deleteMany(f) findOneAndDelete(f) | Delete | Delete |
{ $push: { tags: 'x' } } { $addToSet: ... } { $pull: ... } | Array updates | Arrays |
'items.$.qty' 'items.$[].x' 'items.$[i].x' + arrayFilters | Update array elements | Arrays |
Modelling & performance
| Syntax | What it does | Lesson |
|---|---|---|
{ address: { city: 'York' } } vs { productId: 'p1' } | Embed or reference | Embedded Documents |
createIndex({ status: 1, createdAt: -1 }) | Compound index (ESR order) | Indexes |
createIndex({ email: 1 }, { unique: true }) | Unique index | Indexes |
createIndex({ at: 1 }, { expireAfterSeconds: 3600 }) | TTL index | Indexes |
| Computed, subset, bucket, polymorphic | Schema design patterns | Schema Design |
createCollection('c', { validator: { $jsonSchema: { ... } } }) | Schema validation | Validation |
createIndex({ title: 'text' }) { $text: { $search: 'lamp' } } | Text search | Text Search |
find(q).explain('executionStats') | Check the query plan | Performance & explain |
Aggregation
| Syntax | What it does | Lesson |
|---|---|---|
aggregate([{ $match }, { $group }, { $sort }]) | Pipeline | Aggregation Basics |
{ $group: { _id: '$cat', n: { $sum: 1 }, total: { $sum: '$amount' } } } | Group and total | Aggregation Basics |
{ $unwind: '$items' } { $sortByCount: '$x' } | Flatten arrays, count values | Aggregation Stages |
{ $bucket: ... } { $facet: { ... } } { $merge: ... } | Ranges, multiple results, save | Aggregation Stages |
{ $lookup: { from, localField, foreignField, as } } | Join | $lookup Joins |
Advanced MongoDB
| Syntax | What it does | Lesson |
|---|---|---|
session.withTransaction(() => { ... }) | Multi-document transaction | Transactions |
new MongoClient(uri) await coll.find(q).toArray() | Node.js driver | Node.js Driver |
new Schema({ ... }) Model.find().populate('ref').lean() | Mongoose | Mongoose |
rs.status() { writeConcern: { w: 'majority' } } | Replica sets | Replication |
sh.shardCollection('db.c', { key: 'hashed' }) | Sharding | Sharding |
db.createUser({ user, pwd: passwordPrompt(), roles }) | Users and roles | Security & Users |
mongodump --gzip --archive=f.gz mongorestore | Backup and restore | Backup & Monitoring |
How to use this MongoDB cheat sheet
This MongoDB cheat sheet collects the commands you'll reach for most often, in the same order as the course: mongosh basics, CRUD, query operators, projection and sorting, update operators, arrays, indexes, aggregation, joins, validation, text search, transactions, the Node.js driver and operations. Each row links to the lesson that explains it with examples and common mistakes.
Keep it open while you work. When you can't remember the shape of an upsert, how $elemMatch differs from dot notation, or which accumulator collects unique values, a quick look here is faster than a search. Type part of a keyword into the filter box to jump straight to it, or print the page and keep it beside your keyboard.
MongoDB gotchas worth remembering
- Update operators are required.
updateOne({ _id: id }, { name: "Ana" })is rejected by modern drivers. Wrap the change in$set, otherwise you'd be asking MongoDB to replace the whole document. UsereplaceOnewhen replacement is what you really want. - Filters on arrays match any element.
{ tags: "sale" }finds documents where any tag is "sale". When two conditions must be true of the same array element, use$elemMatch. - ObjectId is not a string. Querying
{ _id: "65f1..." }with a plain string finds nothing. Convert it first withnew ObjectId(id)in the shell or driver. - find() returns a cursor. In mongosh it prints the first 20 results; in Node.js you need
.toArray()or afor awaitloop to get the documents. - Projection can't mix styles. Either include fields (
{ name: 1 }) or exclude them ({ password: 0 }), not both, with_idas the only exception. - Order matters in aggregation. Put
$matchand$projectas early as possible so later stages handle fewer, smaller documents, and so$matchcan use an index. - Indexes follow the ESR rule. In a compound index, list fields used for Equality first, then Sort, then Range. Check the result with
explain("executionStats")and look for IXSCAN rather than COLLSCAN. - Deletes are permanent.
deleteMany({})with an empty filter removes every document. Run the same filter withfindfirst to see exactly what will go.
Which sections to learn first
If you're new to MongoDB, you don't need the whole sheet at once. Most day-to-day work uses only a handful of commands: insertOne, find with a filter and projection, updateOne with $set, deleteOne, sort and limit. Learn those until you can write them without looking, and you'll be able to build a working app. Aggregation, transactions, replication and sharding matter more as your data and your team grow, so treat those sections as a reference you'll come back to later rather than something to memorise now.
A quick revision routine
Before an interview or exam, cover the right-hand column of a section and try to write each command from its description. The ones you can't recall are the lessons to revisit, and the matching MongoDB quiz will tell you if the revision worked.
The MongoDB lessons behind this cheat sheet
Beginner
Intermediate
Advanced
Query and write references
Data processing and storage
- 31MongoDB Window Functions
- 32MongoDB Dates and Timezone Buckets
- 33MongoDB Densify and Fill
- 34MongoDB Read-Only Collection Views
- 35MongoDB Materialized Summary Refresh
- 36MongoDB Change Streams and Resume Tokens
- 37MongoDB Time Series Collections
- 38MongoDB GridFS File Streaming
- 39MongoDB Geospatial Queries
- 40MongoDB Multikey Index Limits