$project
$project chooses, renames and computes fields in each document.
In this page:
Syntax
{ $project: { field1: 1, field2: 1, _id: 0, computed: { $multiply: ["$a", "$b"] } } }
$project
Include fields with 1, exclude with 0 and compute new ones with expressions such as $concat, $multiply and $cond. It reshapes documents for the next stage or the final output. $addFields and $set add computed fields while keeping the rest.
Note:
$addFields keeps existing fields; $project replaces the shape.
Example: $project
test> db.people.insertMany([{ _id: 1, first: "Ada", last: "Lovelace", born: 1815 }, { _id: 2, first: "Alan", last: "Turing", born: 1912 }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.people.aggregate([{ $project: { _id: 0, fullName: { $concat: ["$first", " ", "$last"] } } }])
[ { fullName: 'Ada Lovelace' }, { fullName: 'Alan Turing' } ]
test> db.people.aggregate([{ $project: { _id: 0, born: 1, century: { $ceil: { $divide: ["$born", 100] } } } }])
[ { born: 1815, century: 19 }, { born: 1912, century: 20 } ]
test> db.people.aggregate([{ $addFields: { initials: { $concat: [{ $substr: ["$first", 0, 1] }, { $substr: ["$last", 0, 1] }] } } }, { $project: { _id: 0, initials: 1, born: 1 } }])
[ { born: 1815, initials: 'AL' }, { born: 1912, initials: 'AT' } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Forgetting _id is included by default
- Mixing include and exclude
- Using $project when $addFields is simpler
Chapter Summary
- $project reshapes documents
- 1 includes and 0 excludes
- Expressions compute new fields
- $addFields keeps the rest
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: