Skip to content

Results, Sorting & Pagination

Projection Patterns

Inclusion versus exclusion, slicing arrays, and keeping API payloads small.

IntermediateAbout 4 minutes

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 }
)
List view: names only, plus one nested field
db.orders.find(
  { status: "completed" },
  { items: { $slice: 3 }, amount: 1, status: 1 }
)

db.orders.find(
  { status: "completed" },
  { items: { $slice: -1 } }   // last element only
)
Do not send 200 line items to a list API — $slice first/last N
db.orders.find(
  { "items.name": "USB-C Cable" },
  { items: { $elemMatch: { name: "USB-C Cable" } }, amount: 1 }
)
Projection $elemMatch: only matching items in the returned array

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?

Think about it first.

Practice

Related lessons