MongoDB Associate Developer · Node.js track

MongoDB concept library

Use these original notes to connect MongoDB concepts to the code you write. Each section has a compact example, a common point of confusion, and a link to the MongoDB reference. Treat these notes as a study aid and check current official exam objectives as you prepare.

A · Queries and changes

CRUD: shape a query around the document

A

MongoDB CRUD methods operate on documents in a collection. A filter describes which records qualify. Comparison operators such as $gte and $in belong inside a field condition; logical operators such as $or combine conditions.

db.orders.find(
  { status: "paid", total: { $gte: 100 } },
  { customer: 1, total: 1 }
).sort({ total: -1 })

Read the pieces

  • The filter selects paid orders with a total of at least 100.
  • The projection includes requested fields; MongoDB includes _id unless you explicitly exclude it.
  • The sort uses descending order. Add a stable tie-breaker when page order must remain deterministic.
Common confusion: updateOne() changes one matching document; updateMany() changes every match. Operators such as $set update selected fields, while a replacement document has different semantics.

Worked case: expire unpaid orders safely

Cancel orders still pending after their payment deadline. Including the current state in the filter makes a retry skip orders paid in the meantime.

db.orders.updateMany(
  { status: "pending", paymentDueAt: { $lt: now } },
  { $set: { status: "cancelled", cancelledAt: now } }
)
Why the tempting answer fails: Replacing with { status: "cancelled" } can discard other fields; updateOne() leaves other expired orders unchanged.
In production: preview with countDocuments(), make the transition safe to retry, and inspect matchedCount. Multi-document updates are atomic per document; use a transaction only if the whole group must succeed together.
B · Application code

Node.js driver: manage a client and its work

B

A MongoClient represents a connection pool and is commonly reused across requests. Create it during startup, connect once, and close it when the process shuts down. Driver calls are asynchronous; await the operation whose result you need.

const client = new MongoClient(uri);
await client.connect();
try {
  const orders = client.db("shop").collection("orders");
  const order = await orders.findOne({ _id: orderId });
} finally {
  await client.close();
}

Remember

  • find() returns a cursor, not an array. Use toArray() for a bounded result set, or iterate when results may be large.
  • Await writes when later work depends on completion or result counts.
  • Sessions provide transaction context. Every operation in a transaction must use the same session.
Common confusion: opening a new client for every request throws away pooling and increases connection churn. Reuse the client and define its lifecycle.

Worked case: return one page without loading everything

An endpoint needs 25 recent orders. find() creates a cursor; consuming it retrieves documents.

const cursor = orders.find({ customerId }, {
  projection: { total: 1, placedAt: 1 },
  sort: { placedAt: -1, _id: -1 }, limit: 25
});
for await (const order of cursor) send(order);
Why the tempting answer fails: await orders.find(...) does not turn a cursor into an array. An unbounded toArray() can use far more application memory than intended.
In production: reuse one MongoClient per process so requests share connection pools. Bound user-facing reads and close the client during graceful shutdown.
C · Query performance

Indexes: trade write cost for faster reads

C

An index stores an ordered representation of selected field values so MongoDB can find documents without scanning the whole collection. Indexes improve supported reads, but inserts and updates also maintain them.

db.orders.createIndex({ status: 1, createdAt: -1 })
db.orders.find({ status: "paid" }).sort({ createdAt: -1 })

Compound index order matters

A compound index can support queries using its leading fields. Equality, sort, and range fields often guide field order, but selectivity and query shape matter; verify the real plan with explain().

  • A unique index enforces uniqueness for indexed keys.
  • A multikey index is created when an indexed field contains an array.
  • A TTL index removes eligible documents after a configured time; it is not an exact real-time timer.
Common confusion: adding more indexes is not free. Check query plans and write volume, and remove indexes that do not serve a real access pattern.

Worked case: support a filter and sort together

A dashboard lists the newest paid orders. Test an index whose leading field matches the equality filter and whose next field supports the sort.

db.orders.createIndex({ status: 1, createdAt: -1 })
db.orders.find({ status: "paid" })
  .sort({ createdAt: -1 }).limit(20)
  .explain("executionStats")
Why the tempting answer fails: An index led by an unrelated field may not narrow this query well. Even a plausible index is not guaranteed to be selected by the query planner.
In production: compare nReturned, totalKeysExamined, and totalDocsExamined with realistic data. Indexes use storage and add work to writes, so keep ones that serve measured access patterns.
D · Database foundations

MongoDB overview: documents and deployment

D

MongoDB stores BSON documents in collections. BSON is a binary serialization with additional types, including dates and 64-bit integers. A database groups collections; a collection can hold documents whose fields evolve over time.

{
  _id: ObjectId("..."),
  customer: { id: 42, name: "Mina" },
  placedAt: ISODate("2026-10-01T09:00:00Z"),
  total: Decimal128("128.50")
}

Availability and scale

  • A replica set maintains copies of data and elects a primary for writes. Replication supports availability and redundancy.
  • Sharding distributes data across shards to scale storage and throughput. A shard key determines document distribution.
  • Atlas is MongoDB's managed cloud service; self-managed deployments give operators more infrastructure responsibility.
Common confusion: replication and sharding solve different problems. Replication copies data for availability; sharding partitions data for distribution and scale.

Worked case: separate failover from distribution

A service first needs to survive a host failure, then spread a growing workload across machines. Replica sets keep copies and elect a primary; sharding distributes data according to a shard key. Shards commonly use replica sets too.

Replica set → copies + primary election
Sharding    → partitions + shard key
Atlas       → managed deployment option
Why the tempting answer fails: Replication alone does not partition data to add shard capacity. Sharding is not the same as redundant copies, and neither replaces a backup.
In production: choose a shard key from query and growth patterns. Accidental deletes are replicated too, so plan backup and recovery separately.
E · Application data

Data modeling: design for access patterns

E

Start with the questions the application asks and how often it asks them. Embedding related data can make a common read a single-document operation. Referencing can reduce duplication or keep a growing relationship in a separate collection.

{
  _id: 9001,
  customerId: 42,
  items: [{ sku: "book-1", quantity: 2, unitPrice: 18 }]
}

Choose with growth in mind

  • Embed when child data is bounded, belongs to the parent, and is commonly read together.
  • Reference when records grow without a practical bound, are shared by many parents, or are read independently.
  • Denormalize selectively when faster reads justify keeping duplicated values in sync.
  • Schema validation can enforce expected shapes while an application evolves deliberately.
Common confusion: document databases still need deliberate schemas. Flexible storage does not decide which fields belong together or how updates stay consistent.

Worked case: preserve the price paid on an order

An order page needs its line items and checkout price. Embed a bounded snapshot in the order; keep the shared product catalog as the source of current details.

{
  _id: 9001, customerId: 42,
  items: [{ sku: "book-1", title: "MongoDB Basics",
            quantity: 2, unitPriceAtPurchase: 18 }]
}
Why the tempting answer fails: Looking up only the current catalog price can change how an old receipt appears. Embedding every order ever made in a customer document creates an unbounded array.
In production: snapshot values that must remain historically true, and reference canonical records for current details. Decide which copy is authoritative for each field.
F · Developer workflow

Tools: pick the right view for the task

F

MongoDB tools cover different parts of a development workflow. mongosh runs commands interactively, Compass provides a visual way to explore data, and Atlas UI manages cloud resources.

  • Use mongosh to test a query or inspect server information with commands.
  • Use Compass to browse documents, build filters, and inspect indexes visually.
  • Use Atlas UI for managed deployments, database access controls, monitoring, and cluster configuration.
  • Use application drivers for repeatable production operations; manual console work is not an application integration strategy.
Study prompt: Compare a visual workflow with a scriptable one. The right tool depends on repeatability, context, and who needs to operate it.

Worked case: investigate a slow query, then ship a fix

Use mongosh or Compass to inspect a representative query and plan. Use a driver for repeatable application requests and Atlas UI to manage a hosted cluster and its access.

db.orders.find({ status: "paid" })
  .sort({ createdAt: -1 }).limit(20)
  .explain("executionStats")
Why the tempting answer fails: Compass is a client, not the database server. Atlas is the managed service and a driver is the application interface; they have different jobs.
In production: verify plans against realistic data, then use the normal change process for an index. Give each operator only the database permissions the task needs.