Skip to content

CRUD

Projection

Return only the fields you need — and why `_id` is included unless you turn it off.

BeginnerAbout 4 minutes

A projection is the second argument to find / findOne. It cuts the document down before it leaves the server. That is cheaper than fetching Rahul's whole profile and deleting keys in JavaScript.

db.users.find(
  { city: "Bangalore" },
  { _id: 0, name: 1, age: 1 }
)
Keep name and age. Drop _id — it is included unless you say otherwise.
{ name: "Rahul", age: 28 }
{ name: "Priya", age: 26 }

Inclusion vs exclusion

  • Inclusion{ name: 1, email: 1 } keeps those fields. _id still comes along unless you add _id: 0.
  • Exclusion{ passwordHash: 0, resume: 0 } drops those and keeps the rest.
  • You cannot mix them in one projection, except _id: 0 with an inclusion list. { name: 1, age: 0 } is an error.
SELECT name, age FROM users WHERE city = 'Bangalore';
SQL names columns in SELECT. MongoDB names them in the projection.

APIs should project. A user document will grow — skills, addresses, tokens — and a list endpoint does not need them. Covering indexes and $slice on arrays come later; the rule now is: ask for the fields you will actually send.

Interview question

Why project on the server instead of stripping fields in application code?

Think about it first.

Practice

These problems are a filter plus a projection. Drop `_id`.