Skip to content

Interview Revision

Revision: Data Modeling and Indexes

Embed vs reference, ESR, compound indexes, and explain() output.

AdvancedAbout 7 minutes
  • Access pattern first. Loaded together → together in the document.
  • Embed. 1:1 / 1:few, owned, bounded — address, order.items (snapshot unitPrice).
  • Reference. Unbounded or queried alone — orders.userId. Array of ids only if capped.
  • 16MB. No cap on an array → child collection. Multikey = one index key per element.
  • Validation. $jsonSchema on the collection. Does not migrate old docs.
  • Index. B-tree. _id already unique. Each extra index costs writes + RAM.
  • Compound. Left prefix or nothing. { userId, createdAt } does not serve { status }.
  • ESR. Equality, then sort, then range. Sort + range on the same field → one key.
  • Unique. Database constraint; 11000. Null/missing needs partial/sparse.
  • explain('executionStats'). Examined vs returned. COLLSCAN vs IXSCAN+FETCH. Covered = IXSCAN, no FETCH, _id: 0. SORT in the plan = index did not provide order.
db.orders.createIndex({ userId: 1, createdAt: -1 })
db.orders.find({ userId }).sort({ createdAt: -1 })

db.users.find({ city: "Bangalore" }).explain("executionStats")
Say the index, then the query

Interview question

How do you decide between embedding and referencing?

Think about it first.

Interview question

How does compound index field order work? What is ESR?

Think about it first.

Interview question

A query is slow. What do you look at first?

Think about it first.

Practice