Shape results: include/exclude fields, sort with indexes in mind, paginate with skip/limit or range queries.
Projection
db.products.find(
{ category: 'tools' },
{ name: 1, price: 1, _id: 0 }
)Practice: Use practice database in mongosh.
Sort and limit
db.products.find({ category: 'tools' })
.sort({ price: -1, name: 1 })
.limit(10)
Pagination pattern
// Prefer keyset pagination for large offsets:
db.products.find({ _id: { $gt: lastId } }).sort({ _id: 1 }).limit(20)Large skip values get slow—use range on indexed field instead.
Important interview questions and answers
- Q: Projection 1 vs 0?
A: Cannot mix inclusion and exclusion except _id. - Q: skip(10000) problem?
A: Server still walks skipped docs—expensive at scale.
Self-check
- Return name and price only.
- Why keyset pagination over skip?
Tip: Prefer keyset pagination over large skip() on indexed _id or createdAt.
Interview prep
- skip cost?
- Large skip walks many docs—use keyset pagination.
- Mixed projection?
- Cannot mix inclusion and exclusion except _id.