MongoDBPrintable

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.

Back to the MongoDB tutorial

Basics

SyntaxWhat it doesLesson
use shop show dbs show collectionsSwitch and list databases and collectionsIntroduction
db.c.insertOne({ ... }) db.c.insertMany([...])Insert documentsInsert
db.c.find({ status: 'paid' }) db.c.findOne({ _id })Find documentsFind & Queries
{ 'address.city': 'Leeds' } { tags: 'gift' }Nested fields and array containsFind & Queries
db.c.countDocuments(f) db.c.distinct('field')Count and list unique valuesFind & Queries
Decimal128('19.99') ISODate('2026-03-01') { $type: 'string' }TypesData Types

Queries & results

SyntaxWhat it doesLesson
{ price: { $gte: 10, $lte: 50 } }RangeQuery Operators
{ status: { $in: ['a', 'b'] } } { $or: [ ... ] }Lists and alternativesQuery Operators
{ phone: { $exists: false } } { name: { $regex: '^a', $options: 'i' } }Presence and patternsQuery Operators
{ items: { $elemMatch: { sku: 'X', qty: { $gt: 1 } } } }One array element meets several conditionsQuery Operators
find(f, { name: 1, _id: 0 })ProjectionProjection & Sorting
.sort({ price: -1, _id: 1 }).skip(20).limit(20)Sort and pageProjection & Sorting

Writes

SyntaxWhat it doesLesson
updateOne(f, { $set: { a: 1 }, $inc: { n: 1 } })Update fieldsUpdate
updateOne(f, u, { upsert: true }) $setOnInsertInsert if missingUpdate
findOneAndUpdate(f, u, { returnDocument: 'after' })Update and returnUpdate
deleteOne(f) deleteMany(f) findOneAndDelete(f)DeleteDelete
{ $push: { tags: 'x' } } { $addToSet: ... } { $pull: ... }Array updatesArrays
'items.$.qty' 'items.$[].x' 'items.$[i].x' + arrayFiltersUpdate array elementsArrays

Modelling & performance

SyntaxWhat it doesLesson
{ address: { city: 'York' } } vs { productId: 'p1' }Embed or referenceEmbedded Documents
createIndex({ status: 1, createdAt: -1 })Compound index (ESR order)Indexes
createIndex({ email: 1 }, { unique: true })Unique indexIndexes
createIndex({ at: 1 }, { expireAfterSeconds: 3600 })TTL indexIndexes
Computed, subset, bucket, polymorphicSchema design patternsSchema Design
createCollection('c', { validator: { $jsonSchema: { ... } } })Schema validationValidation
createIndex({ title: 'text' }) { $text: { $search: 'lamp' } }Text searchText Search
find(q).explain('executionStats')Check the query planPerformance & explain

Aggregation

SyntaxWhat it doesLesson
aggregate([{ $match }, { $group }, { $sort }])PipelineAggregation Basics
{ $group: { _id: '$cat', n: { $sum: 1 }, total: { $sum: '$amount' } } }Group and totalAggregation Basics
{ $unwind: '$items' } { $sortByCount: '$x' }Flatten arrays, count valuesAggregation Stages
{ $bucket: ... } { $facet: { ... } } { $merge: ... }Ranges, multiple results, saveAggregation Stages
{ $lookup: { from, localField, foreignField, as } }Join$lookup Joins

Advanced MongoDB

SyntaxWhat it doesLesson
session.withTransaction(() => { ... })Multi-document transactionTransactions
new MongoClient(uri) await coll.find(q).toArray()Node.js driverNode.js Driver
new Schema({ ... }) Model.find().populate('ref').lean()MongooseMongoose
rs.status() { writeConcern: { w: 'majority' } }Replica setsReplication
sh.shardCollection('db.c', { key: 'hashed' })ShardingSharding
db.createUser({ user, pwd: passwordPrompt(), roles })Users and rolesSecurity & Users
mongodump --gzip --archive=f.gz mongorestoreBackup and restoreBackup & 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. Use replaceOne when 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 with new 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 a for await loop to get the documents.
  • Projection can't mix styles. Either include fields ({ name: 1 }) or exclude them ({ password: 0 }), not both, with _id as the only exception.
  • Order matters in aggregation. Put $match and $project as early as possible so later stages handle fewer, smaller documents, and so $match can 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 with find first 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