How to Use $project in Aggregation in MongoDB: Syntax and Examples
In MongoDB aggregation, use the
$project stage to specify which fields to include, exclude, or add new computed fields in the output documents. It reshapes each document by controlling the fields passed to the next stage or final result. You define fields with 1 to include, 0 to exclude, or expressions to create new fields.Syntax
The $project stage takes an object where keys are field names and values specify how to handle those fields:
- 1 to include a field
- 0 to exclude a field
- Expressions to create or transform fields
Example syntax:
mongodb
db.collection.aggregate([
{ $project: {
field1: 1, // include field1
field2: 0, // exclude field2
newField: { $add: ["$field3", 10] } // create newField by adding 10 to field3
}}
])Example
This example shows how to use $project to include only name and totalScore fields, where totalScore is computed by adding math and english scores.
mongodb
db.students.aggregate([
{ $project: {
_id: 0,
name: 1,
totalScore: { $add: ["$math", "$english"] }
}}
])Output
[
{ "name": "Alice", "totalScore": 180 },
{ "name": "Bob", "totalScore": 170 }
]
Common Pitfalls
Common mistakes when using $project include:
- Mixing inclusion and exclusion of fields (except for
_id) causes errors. - Forgetting to exclude
_idif you don't want it in output (it is included by default). - Using incorrect field paths or missing
$before field names in expressions.
mongodb
/* Wrong: mixing inclusion and exclusion */ db.collection.aggregate([ { $project: { field1: 1, field2: 0 } } ]) /* Right: use only inclusion or only exclusion */ db.collection.aggregate([ { $project: { field1: 1, field3: 1 } } ])
Quick Reference
| Usage | Description | Example |
|---|---|---|
| Include field | Add field to output | { fieldName: 1 } |
| Exclude field | Remove field from output | { fieldName: 0 } |
| Create new field | Add computed field | { newField: { $add: ["$a", "$b"] } } |
| Exclude _id | Remove _id from output | { _id: 0 } |
Key Takeaways
Use $project to control which fields appear in aggregation output by including or excluding them.
Do not mix inclusion and exclusion of fields in the same $project stage except for _id.
Use expressions inside $project to create new fields or transform existing ones.
Remember _id is included by default; exclude it explicitly if not needed.
Field names in expressions must be prefixed with $ to reference document fields.