Results, Sorting & Pagination
Projection Patterns
Inclusion versus exclusion, slicing arrays, and keeping API payloads small.
CRUD already covered inclusion, exclusion, and _id: 0. This is how list endpoints stay small: nested paths, `$slice` on arrays, `$elemMatch` in the projection (not only in the filter).
db.users.find(
{ city: "Bangalore" },
{ _id: 0, name: 1, "address.pin": 1 }
)db.orders.find(
{ status: "completed" },
{ items: { $slice: 3 }, amount: 1, status: 1 }
)
db.orders.find(
{ status: "completed" },
{ items: { $slice: -1 } } // last element only
)db.orders.find(
{ "items.name": "USB-C Cable" },
{ items: { $elemMatch: { name: "USB-C Cable" } }, amount: 1 }
)Inclusion still cannot mix with exclusion except _id. $slice / $elemMatch on a field count as that field's projection. A covered query (index-only) is an Indexing topic — the habit to build now is: every find in an API has an explicit projection.
Interview question
How do you keep an array field from exploding an API response?
Project it. $slice for first/last N elements. $elemMatch in the projection to return only matching elements. I would not send the full items array on a list of orders.
Practice