Skip to content

MongoDB Cheat Sheet

5–15 minute quick revision. Scan the reminders. Click anything rusty to jump into Learn.

MongoDB Mental Model

Learn

Data

  1. Database
  2. Collection
  3. Document
  4. Field

Runtime

  1. Application
  2. MongoDB Driver
  3. Connection Pool
  4. MongoDB

Documents are BSON (typed JSON). `_id` is required. One document write is atomic.

  • vs SQLdocument-oriented, not tables and rows
  • BSONObjectId, Date, Decimal128, ints — JSON cannot hold these
  • _idimmutable unique key; usually an ObjectId

CRUD

Learn
Insert
db.users.insertOne({
  name: "Rahul",
  age: 28,
  city: "Bangalore"
})
Find
db.users.find({ age: { $gt: 25 } })
db.users.findOne({ email: "rahul@example.com" })
Update
db.users.updateOne(
  { _id: ObjectId("64a1b2c3d4e5f6a7b8c90001") },
  { $set: { isActive: false } }
)
Delete
db.users.deleteOne({ _id: ObjectId("64a1b2c3d4e5f6a7b8c90001") })

Also useful

Query Operators

Learn

Comparison

Logical

  • $andall conditions
  • $orany condition
  • $nornone of the conditions
  • $notnegates a condition

Element

Evaluation

  • $regexstring pattern
  • $exprcompare fields on the same document

`$in` on one field beats `$or` of equalities. `$or` across different fields needs an index per branch.

Projection

Learn
db.users.find(
  { city: "Bangalore" },
  { name: 1, email: 1 }
)
  • 1include the field
  • 0exclude the field
  • _idreturned unless you set `_id: 0`

Do not mix include and exclude, except excluding `_id` on an include list. Projection can make a query covered.

Practice projectionReturn only selected fields

Arrays & Nested Documents

Learn
Nested field
{ "address.city": "Bangalore" }
Array contains value
{ skills: "Node.js" }
All values present
{ skills: { $all: ["Node.js", "MongoDB"] } }
Same array element must satisfy all conditions
{
  skills: {
    $elemMatch: {
      name: "Node.js",
      experience: { $gt: 2 }
    }
  }
}

Dot notation on arrays of objects can match different elements. Use `$elemMatch` when one element must satisfy every condition.

Array updates

Practice array queriesFind active sellers

Update Operators

Learn
Most common
db.products.updateOne(
  { name: "Mechanical Keyboard" },
  { $set: { stock: 19 }, $inc: { sold: 1 } }
)

Sorting & Pagination

Learn
db.orders.find({ status: "completed" })
  .sort({ createdAt: -1 })
  .limit(10)
  .skip(20)
Cursor pagination
db.orders.find({ _id: { $gt: lastId } })
  .sort({ _id: 1 })
  .limit(10)

`skip(n)` still walks n documents. Cost grows with page number. Interview takeaway: offset pagination does not scale.

Aggregation

Learn
  1. Documents
  2. $match
  3. $group
  4. $sort
  5. $limit
  6. Result

Stages

Top 3 customers by spend
db.orders.aggregate([
  { $match: { status: "completed" } },
  {
    $group: {
      _id: "$userId",
      totalSpent: { $sum: "$amount" }
    }
  },
  { $sort: { totalSpent: -1 } },
  { $limit: 3 }
])

`$match` early. `$lookup` is a left outer join — index the foreign field, and do not use it as a default for every relationship.

Aggregation Expressions

Learn

Arithmetic

Conditional

Array

String

Date

Practice expression pipelinesMonthly revenueAverage salary by department

Data Modeling

Learn

Embed when

  • data is read together
  • one-to-few
  • child data is bounded
  • you want a single-document read

Reference when

  • data is large
  • data is independently accessed
  • relationship is many-to-many
  • the relationship can grow without bound
  • Embeddingfewer queries · data can duplicate · document can grow
  • Referencingnormalized · extra queries / `$lookup` · independent documents

Start from the access pattern. Order `items` embed. A user's orders reference. Documents cap at 16MB.

Indexing

Learn
Single field
db.users.createIndex({ email: 1 })
Compound
db.orders.createIndex({ userId: 1, createdAt: -1 })
Unique
db.users.createIndex({ email: 1 }, { unique: true })
TTL
db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 3600 }
)
  • Readsindexes speed them up
  • Coststorage + write overhead
  • ESREquality → Sort → Range
  • Prefix{a,b,c} serves a, a+b, a+b+c — not b alone

Query Performance

Learn
  1. explain()
  2. executionStats
db.orders.find({ status: "delivered" }).explain("executionStats")

Prefer IXSCAN for selective queries. COLLSCAN is not automatically wrong — a tiny collection or a query that must read most documents can still scan. Judge the plan against the query and the dataset. Look at examined vs returned.

Atomicity & Transactions

Learn
Commit
session.startTransaction()
// operations
await session.commitTransaction()
Failure
await session.abortTransaction()

Transactions give atomicity across multiple operations. Use them when necessary — not as the default write path. Prefer a model where one document write is enough.

Concurrency

Learn
Do not read-then-write stock
// race
const product = await products.findOne({ _id })
await products.updateOne(
  { _id },
  { $set: { stock: product.stock - 1 } }
)

// atomic
await products.updateOne(
  { _id, stock: { $gt: 0 } },
  { $inc: { stock: -1 } }
)

Node.js + MongoDB

Learn
const client = new MongoClient(MONGO_URI);

await client.connect();

const db = client.db("app");
const users = db.collection("users");

const user = await users.findOne({ email });

Do not create a new MongoDB connection for every request. Reuse the MongoClient / connection pool.

Core objects

Mongoose

Learn

Common methods

Worth remembering

Production MongoDB

Learn
  1. Primary
  2. Secondaries

Security

Learn

Do

  • store credentials in environment variables
  • validate user input before it becomes a query
  • restrict network access
  • use least-privilege database roles
  • protect connection strings

Don't

  • commit secrets or `.env` files
  • expose the database to the public internet
  • give an app user cluster-admin
  • build queries from raw request bodies

Common Mistakes

Learn
  • No indexes on frequently queried fields

    Index the equality and sort fields your hot queries actually use. Learn

  • Too many indexes

    Every index costs writes and RAM. Drop unused ones. Learn

  • Using skip() for massive pagination

    Use a cursor on `_id` or a unique sorted field. Learn

  • Unbounded arrays

    Reference or bucket once the array can grow without a cap. Learn

  • Returning huge documents

    Project the fields the caller needs. Learn

  • Overusing $lookup

    Embed data that is always read together; lookup is not a default join. Learn

  • Treating flexible schema as “no schema”

    The schema still lives somewhere — usually in application code or validators. Learn

  • Creating a new DB connection per request

    Reuse one MongoClient and its pool. Learn

  • Using transactions unnecessarily

    Model so a single-document write is the common case. Learn

  • Passing a string instead of ObjectId

    Cast with `new ObjectId(id)` (or let Mongoose do it). Learn

  • Not checking explain()

    Read executionStats before guessing an index. Learn

Interview Quick Revision

Learn
  • MongoDB vs SQL

    MongoDB is document-oriented with a flexible document model. SQL is relational with a structured schema.

  • Embedding vs referencing

    Embed when data belongs together and is bounded. Reference when it is independent, large, or unbounded.

  • Index

    Faster reads, paid for with storage and write overhead.

  • Aggregation

    A pipeline of stages that transforms documents.

  • Transactions

    Useful when multiple operations must succeed or fail together.

  • Replica set

    High availability and failover.

  • Sharding

    Horizontal scaling by distributing data across shards.

  • $elemMatch

    All conditions must hold on the same array element.

  • ESR

    Equality fields, then sort, then range.