Goal: Return only the fields you need, not the entire document. Key Idea: In MongoDB,
.find()takes two arguments — the filter, then the projection.
db.collection.find(
{ /* filter — like WHERE */ },
{ /* projection — like SELECT */ }
);| Value | Meaning |
|---|---|
1 |
✅ Include this field |
0 |
❌ Exclude this field |
Rule: You can either include fields (
1) or exclude fields (0) — generally not both in the same projection (except for_id).
SELECT username, email
FROM Users
WHERE status = 'active';db.users.find(
{ status: "active" }, // Stage 1: Filter (WHERE)
{ username: 1, email: 1, _id: 0 } // Stage 2: Projection (SELECT)
);{ username: 1, email: 1, _id: 0 }
// ↑ ↑
// include exclude _id
//
// By default, _id is ALWAYS included.
// You must explicitly set _id: 0 to hide it.// Hide the password field, show everything else
db.users.find(
{ status: "active" },
{ password: 0 }
);db.users.find(
{}, // No filter = match all documents
{ name: 1, _id: 0 }
);_idis the only field you can mix with an inclusion projection (e.g.,{ name: 1, _id: 0 }).- Mixing
0and1for other fields in the same projection will throw an error. - An empty filter
{}means "match everything" — likeSELECTwith noWHERE.