Skip to content
Production Reference • 8 Architectural Modules

MongoDB Performance & Architecture Cheatsheet

Production-tested patterns for ESR index ordering, 100MB aggregation memory boundaries, WiredTiger cache tuning, writeConcern/readConcern guarantees, and change streams.

1. MQL Query & Filtering Operators

High-frequency MQL filter expressions, nested dot notation, and array query operators.

Comparison & Logical Operators

Combine range checks with logical $and, $or, and $in sets.

db.orders.find({
  $or: [
    { status: "completed", total: { $gte: 100, $lte: 500 } },
    { payment: { $in: ["wire", "crypto"] }, priority: "high" }
  ]
});

Nested Field & Subdocument Search

Query nested subdocument attributes using dot notation inside quotes.

db.users.find({
  "contact.address.city": "Seattle",
  "preferences.notifications.email": true
});

Array Element Matching ($elemMatch)

Match documents where at least one array element satisfies ALL conditions simultaneously.

db.orders.find({
  items: {
    $elemMatch: { price: { $gt: 50 }, quantity: { $gte: 2 } }
  }
});
Caveat / Pitfall: Querying { "items.price": { $gt: 50 }, "items.quantity": { $gte: 2 } } matches if one item has high price and another item has high quantity!

2. Aggregation Pipeline & Transformations

Multi-stage pipeline recipes for grouping, reshaping, unwinding, and joining collections.

Filter, Group, and Sort Pattern

The canonical analytical pipeline: filter early with $match, summarize with $group, sort with $sort.

db.orders.aggregate([
  { $match: { status: "completed", created_at: { $gte: ISODate("2026-01-01") } } },
  { $group: { _id: "$category", totalRevenue: { $sum: "$total" }, orderCount: { $sum: 1 } } },
  { $sort: { totalRevenue: -1 } }
]);

Non-Destructive Field Injection ($set)

Append calculated fields without discarding other document attributes.

db.products.aggregate([
  {
    $set: {
      totalInventoryValue: { $multiply: ["$price", "$stock"] },
      isLowStock: { $cond: [ { $lt: ["$stock", 10] }, true, false ] }
    }
  }
]);

Safe Array Flattening with $unwind

Deconstruct array elements while preserving documents with empty lists.

db.orders.aggregate([
  {
    $unwind: {
      path: "$items",
      preserveNullAndEmptyArrays: true
    }
  },
  { $group: { _id: "$items.name", unitsSold: { $sum: "$items.quantity" } } }
]);

3. Index Optimization & The ESR Rule

Compound index patterns, partial indexes, and preventing in-memory sort spills.

The ESR (Equality, Sort, Range) Pattern

Order compound indexes: Equality fields first, Sort fields second, Range fields last.

// For query: .find({ tenant_id: 1, total: { $gt: 100 } }).sort({ date: -1 })
// Optimal Index:
db.orders.createIndex({ tenant_id: 1, date: -1, total: 1 });
Caveat / Pitfall: Placing range total before sort date forces MongoDB to perform a blocking 100MB in-memory sort.

Partial Index for Skewed Datasets

Index only documents matching a specific status filter to save 90% of index RAM.

db.orders.createIndex(
  { created_at: 1 },
  { partialFilterExpression: { status: "unprocessed" } }
);

Covered Query Pattern (Zero Document Fetches)

Satisfy filter and projection entirely from index B-Trees, suppressing _id: 0.

// Index: { username: 1, email: 1 }
db.users.find(
  { username: "alice" },
  { _id: 0, username: 1, email: 1 }
);

4. WiredTiger Storage & Memory Tuning

Cache sizing, dirty page monitoring, and checkpoint latency controls.

Check Cache & Dirty Page Pressure

Verify if dirty pages are approaching the dangerous 20% threshold where client threads stall.

const c = db.serverStatus().wiredTiger.cache;
const totalMb = c["bytes currently in the cache"] / 1024 / 1024;
const dirtyMb = c["tracked dirty bytes in the cache"] / 1024 / 1024;
print(`Cache: ${totalMb.toFixed(0)}MB | Dirty: ${dirtyMb.toFixed(0)}MB (${(dirtyMb/totalMb*100).toFixed(1)}%)`);

WiredTiger Engine Configuration in mongod.conf

Set dedicated memory size in gigabytes leaving headroom for OS cache.

storage:
  engine: wiredTiger
  wiredTiger:
    engineConfig:
      cacheSizeGB: 16
    collectionConfig:
      blockCompressor: zstd

5. Write & Read Concern Reference Matrix

Balancing latency against durability, consistency, and election rollback safety.

Zero-Data-Loss Write Concern

Guarantees the write is replicated to a majority of voting nodes and flushed to disk journal.

db.transactions.insertOne(
  { from: "A", to: "B", amount: 500 },
  { writeConcern: { w: "majority", j: true, wtimeout: 5000 } }
);
Caveat / Pitfall: Omitting wtimeout can cause client application connections to hang indefinitely during network splits.

Read Concern "majority" to Avoid Rollbacks

Read from in-memory WiredTiger snapshots committed by a majority of replica members.

db.transactions.find({ status: "cleared" }).readConcern("majority");

6. Replica Set Administration & Failover

Step-downs, reconfigurations, member priorities, and monitoring replication lag.

Graceful Primary Step-Down for Rolling Maintenance

Step down the active primary for 60 seconds to safely promote a secondary with zero downtime.

rs.stepDown(60);

Check Secondary Replication Lag

Identify nodes lagging behind the primary in seconds.

rs.printSecondaryReplicationInfo();

Configure Member Priority and Voting

Set priority: 0 to create a non-electable dedicated reporting node.

const cfg = rs.conf();
cfg.members[2].priority = 0; // Cannot become primary
cfg.members[2].tags = { "role": "analytics" };
rs.reconfig(cfg);

7. Sharding Operations & Chunk Management

Enabling sharding, selecting hashed/range keys, and monitoring the balancer.

Hashed Sharding for Uniform Write Distribution

Distribute monotonically increasing IDs evenly across all cluster shards.

sh.enableSharding("iot_db");
sh.shardCollection("iot_db.readings", { "sensor_id": "hashed" });

Check Chunk Balancer Status & Schedule Window

Restrict automatic chunk migrations to off-peak hours.

sh.setBalancerState(true);
db.getSiblingDB("config").settings.updateOne(
  { _id: "balancer" },
  { $set: { activeWindow: { start: "02:00", stop: "05:00" } } },
  { upsert: true }
);

8. Database Profiler, Slow Queries & explain()

Capture slow queries exceeding thresholds and dissect query execution plans.

Enable Database Profiler for Queries > 50ms

Log slow operations into system.profile collection for diagnostic tuning.

db.setProfilingLevel(1, { slowms: 50 });
// View recent slow queries:
db.system.profile.find({ millis: { $gt: 50 } }).sort({ ts: -1 }).limit(5);

Run explain("executionStats") for Plan Analysis

Inspect totalKeysExamined, totalDocsExamined, and detect COLLSCAN / in-memory SORT.

const exp = db.orders.find({ status: "pending" })
  .sort({ created_at: -1 })
  .explain("executionStats");

print("Winning Stage: " + exp.executionStats.executionStages.stage);
print("Keys Examined: " + exp.executionStats.totalKeysExamined);
print("Docs Examined: " + exp.executionStats.totalDocsExamined);