0
0
MongodbHow-ToBeginner · 3 min read

How to Use Projection in MongoDB: Syntax and Examples

In MongoDB, projection is used to specify which fields to include or exclude in the query result. You add a projection document as the second argument to find() or findOne() to control the output fields.
📐

Syntax

The basic syntax for using projection in MongoDB is:

db.collection.find(query, projection)

Here, query filters documents, and projection specifies fields to include (1) or exclude (0).

Note: You cannot mix inclusion and exclusion except for the _id field.

mongodb
db.collection.find({ filter }, { field1: 1, field2: 1, _id: 0 })
💻

Example

This example shows how to find all users but only return their name and email fields, excluding the _id field.

mongodb
db.users.find({}, { name: 1, email: 1, _id: 0 })
Output
[ { "name": "Alice", "email": "alice@example.com" }, { "name": "Bob", "email": "bob@example.com" } ]
⚠️

Common Pitfalls

Common mistakes when using projection include:

  • Mixing inclusion and exclusion of fields (e.g., { name: 1, age: 0 }) which is not allowed except for _id.
  • Forgetting that _id is included by default unless explicitly excluded.
  • Using projection on nested fields incorrectly.
mongodb
/* Wrong: mixing inclusion and exclusion */
db.users.find({}, { name: 1, age: 0 })

/* Correct: only inclusion or exclusion */
db.users.find({}, { name: 1, email: 1, _id: 0 })

/* Or exclude fields only */
db.users.find({}, { password: 0, _id: 0 })
📊

Quick Reference

Projection UsageDescription
{ field: 1 }Include the field in the result
{ field: 0 }Exclude the field from the result
{ _id: 0 }Exclude the _id field (included by default)
Mixing 1 and 0 (except _id)Not allowed, causes error
Projection as second argumentUsed in find() or findOne()

Key Takeaways

Use projection as the second argument in find() to select fields.
Specify fields with 1 to include or 0 to exclude, but don't mix both.
The _id field is included by default; exclude it explicitly if needed.
Projection helps reduce data transfer by returning only needed fields.