CRUD
Projection
Return only the fields you need — and why `_id` is included unless you turn it off.
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 }
){ name: "Rahul", age: 28 }
{ name: "Priya", age: 26 }Inclusion vs exclusion
- Inclusion —
{ name: 1, email: 1 }keeps those fields._idstill 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: 0with an inclusion list.{ name: 1, age: 0 }is an error.
SELECT name, age FROM users WHERE city = 'Bangalore';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?
Less data on the wire, less BSON to decode, and you cannot accidentally serialise a field you meant to drop. _id is returned unless you exclude it. Inclusion and exclusion cannot be mixed except for excluding _id.
Practice
These problems are a filter plus a projection. Drop `_id`.