MongoDB — Cheat Sheet

Tags: mongodb, nosql, aggregation, indexing, transactions, sharding, replication

Level: intermediate

TL;DR: Schema-flexible NoSQL document database optimized for high-throughput reads/writes, horizontal scaling, and rich expressive querying.

Key concepts

BSON document model stores dynamic schemas natively as binary JSON representations.

Primary key _id is auto-generated as an immutable 12-byte ObjectId.

Replica sets provide high availability via automated primary-secondary failover.

Sharding distributes large datasets across multiple clusters using a shard key.

Compound indexes enforce query optimization through strict left-to-right prefix matching.

Aggregation pipeline processes multi-stage data transformations sequentially in memory.

Document-level atomicity guarantees ACID compliance within single documents natively.

Multi-document transactions are supported across replica sets and sharded clusters.

Write concern and read concern define durability and consistency guarantees.

Change streams expose real-time database change notifications using replica oplogs.

Typical questions and ready answers

Q: When would you choose MongoDB over a traditional relational database?R: I pick MongoDB when handling evolving schemas, high ingestion volume, or hierarchical document structures, while relational databases remain my choice for complex multi-table joins.

Q: How do you optimize slow queries in MongoDB?R: I analyze execution statistics using .explain("executionStats") to spot collscans, add targeted compound indexes, and ensure index selectivity covers the filtering keys.

Q: How does MongoDB maintain consistency and replication?R: MongoDB uses replica sets with a single primary receiving writes, which are asynchronously or synchronously replicated to secondary nodes via the capped oplog.rs collection.

Q: What is the difference between embedding and referencing documents?R: I embed data when relationships are 1:1 or bounded 1:N and read together, and I reference ObjectIds when entities have unbounded 1:N or M:N relationships to prevent document bloat.

Q: How do multi-document transactions work in MongoDB?R: They use snapshot isolation across sessions, requiring a two-phase commit internally across nodes, though I design document boundaries first to minimize distributed transaction overhead.

Pitfalls and common mistakes

Exceeding the hard 16 MB maximum document size limit by embedding unbounded arrays.

Missing indexes on foreign reference fields during manual joins via $lookup.

Misunderstanding compound index order where query filters skip the index prefix.

Overusing $lookup repeatedly, turning document collections into an inefficient pseudo-relational model.

Setting overly strict write concerns like w: "majority" on high-throughput paths without latency tolerance.

Running unindexed aggregation stages like $sort that exceed the 100 MB RAM limit without allowDiskUse.

Choosing a monotonic shard key (such as auto-increment IDs) creating unbalanced write hotspots.

Snippets and commandsJavaScript

// Query with projection and sort
db.users.find(
  { status: "active", age: { $gte: 21 } },
  { name: 1, email: 1, _id: 0 }
).sort({ createdAt: -1 }).limit(10);

JavaScript

// Compound index creation
db.orders.createIndex({ customerId: 1, status: 1, createdAt: -1 });

// Inspect query performance execution plan
db.orders.find({ customerId: "u123", status: "completed" }).explain("executionStats");

JavaScript

// Aggregation pipeline: filtering, grouping, sorting
db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: {
      _id: "$customerId",
      totalSpent: { $sum: "$amount" },
      orderCount: { $sum: 1 }
  }},
  { $sort: { totalSpent: -1 } },
  { $limit: 5 }
]);

JavaScript

// Multi-document ACID transaction in Node.js driver
const session = client.startSession();
try {
  await session.withTransaction(async () => {
    await accounts.updateOne({ _id: fromId }, { $inc: { balance: -amount } }, { session });
    await accounts.updateOne({ _id: toId }, { $inc: { balance: amount } }, { session });
  });
} finally {
  await session.endSession();
}

To review

[ ] Index prefix coverage rules and ESR (Equality, Sort, Range) rule.

[ ] Read preferences (primary, primaryPreferred, secondary, secondaryPreferred, nearest).

[ ] Write concerns (w: 1, w: "majority", j: true).

[ ] TTL indexes and Partial/Sparse index configurations.

[ ] WiredTiger storage engine cache sizing and checkpointing.

References

MongoDB Official Manual (docs.mongodb.com)

MongoDB Aggregation Pipeline Quick Reference

WiredTiger Storage Engine Architecture Guide

Jarvis Interviews
Jarvis