Middle · MongoDB with Go

Compound indexes and pagination

Which index supports tenant filtering and newest-first pagination?

Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.

Reveal a strong answer
  1. Start from the query shape: equality predicates, ordering and range conditions. A compound index should support the authorized tenant scope and deterministic sort, often including a unique tie-breaker such as _id.

  2. Inspect explain and representative cardinalities rather than assuming an index is used efficiently because it exists. Extra indexes cost memory and write work; a covered query and a selective query are related but different ideas.

  3. Large skip offsets still walk past work. Prefer keyset pagination using the last sort tuple, with stable semantics when records arrive or change. Tokens must preserve scope and should not permit a different tenant query.

Common trap

Sorting only by a non-unique timestamp can skip or duplicate equal-time rows across pages.

Try it

Records sort by createdAt descending and _id descending within one tenant. What belongs in the page token?

Worked solution

Include both last createdAt and last _id plus the relevant scope/filter identity. The next query uses a lexicographic less-than boundary for that tuple. Verify with equal timestamps and inserts between page requests.

Change the constraint

What consistency promise do you make if a record's sort key changes while the client paginates?

How did you do?

Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.

Not marked. Progress stays on this browser, separate from course completion.

Primary references

Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.