The $project stage lets you choose which fields to keep, remove, or create in your MongoDB query results. It helps you shape the output to show only what you want.
$project stage for shaping output in MongoDB
Introduction
Syntax
MongoDB
db.collection.aggregate([
{ $project: {
field1: 1,
field2: 1,
newField: { $someOperator: "$existingField" },
_id: 0
}}
])Use 1 to include a field and 0 to exclude it.
You can create new fields using expressions inside $project.
Examples
name and age fields, hiding the _id field.MongoDB
db.users.aggregate([
{ $project: { name: 1, age: 1, _id: 0 } }
])totalPrice by multiplying price and quantity.MongoDB
db.orders.aggregate([
{ $project: { totalPrice: { $multiply: ["$price", "$quantity"] }, _id: 0 } }
])name field to productName and includes price.MongoDB
db.products.aggregate([
{ $project: { productName: "$name", price: 1, _id: 0 } }
])Sample Program
This query creates a new field fullName by joining firstName and lastName, includes department, and hides _id.
MongoDB
db.employees.aggregate([
{ $project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
department: 1,
_id: 0
}}
])Important Notes
If you include any field with 1, MongoDB excludes all others by default except _id.
To hide _id, you must explicitly set _id: 0.
You can use many MongoDB expressions inside $project to transform data.
Summary
$project shapes the output by selecting, renaming, or creating fields.
Use 1 to keep fields, 0 to hide them.
You can build new fields using expressions like $concat or $multiply.
Practice
1. What does the
$project stage do in a MongoDB aggregation pipeline?easy
Solution
Step 1: Understand the purpose of
The$project$projectstage is used to control which fields appear in the output documents and how they are shaped.Step 2: Compare with other stages
Filtering is done by$match, sorting by$sort, and grouping by$group. So$projectis for shaping output fields.Final Answer:
It shapes the output by selecting, renaming, or creating fields. -> Option BQuick Check:
$projectshapes output = A [OK]
Hint: Remember: $project controls output fields only [OK]
Common Mistakes:
- Confusing $project with $match for filtering
- Thinking $project sorts documents
- Mixing $project with $group for aggregation
2. Which of the following is the correct syntax to include only the
name and age fields in the output using $project?easy
Solution
Step 1: Recall
To include fields, set them to 1. To exclude, set to 0. Boolean or strings are invalid.$projectsyntax for inclusionStep 2: Check each option
{ $project: { name: 1, age: 1 } } uses 1 for inclusion correctly. { $project: { name: 0, age: 0 } } excludes fields. { $project: { name: true, age: true } } uses true which is invalid. { $project: { name: 'include', age: 'include' } } uses strings which is invalid.Final Answer:
{ $project: { name: 1, age: 1 } } -> Option AQuick Check:
Include fields = 1 in $project [OK]
Hint: Use 1 to include fields, 0 to exclude in $project [OK]
Common Mistakes:
- Using true/false instead of 1/0
- Mixing inclusion and exclusion in same $project
- Using strings instead of numbers for field selection
3. Given the collection documents:
What will be the output of this aggregation?
{ "name": "Alice", "age": 25, "city": "NY" }What will be the output of this aggregation?
[{ $project: { fullName: "$name", ageInMonths: { $multiply: ["$age", 12] }, _id: 0 } }]medium
Solution
Step 1: Understand field renaming and calculation
ThefullNamefield is created by copyingname. TheageInMonthsis calculated by multiplyingageby 12 (25*12=300). The_idis excluded.Step 2: Check output fields
Output hasfullNamewith "Alice" andageInMonthswith 300. Nonameoragefields remain.Final Answer:
[{ "fullName": "Alice", "ageInMonths": 300 }] -> Option DQuick Check:
Rename + multiply age = output [OK]
Hint: Use $multiply to calculate new fields in $project [OK]
Common Mistakes:
- Expecting original fields to remain without including them
- Confusing field names after renaming
- Forgetting to exclude _id if not wanted
4. Identify the error in this
$project stage:{ $project: { fullName: "$name", ageInMonths: { $multiply: ["age", 12] }, _id: 0 } }medium
Solution
Step 1: Check field references in expressions
In MongoDB aggregation, to reference a field inside expressions, prefix with$. Here, "age" is missing$.Step 2: Validate other parts
$multiplyis valid in$project. Excluding_idis allowed. Renaming fields is allowed.Final Answer:
Field name "age" should be prefixed with $ to reference the field. -> Option CQuick Check:
Field references need $ prefix [OK]
Hint: Always prefix field names with $ inside expressions [OK]
Common Mistakes:
- Omitting $ before field names in expressions
- Thinking $multiply is invalid in $project
- Believing _id cannot be excluded
5. You have documents with fields
firstName, lastName, and birthYear. Write a $project stage that outputs fullName as concatenation of first and last names separated by a space, and age calculated as 2024 minus birthYear. Which is the correct stage?hard
Solution
Step 1: Build fullName using $concat with spaces
Use$concatwith"$firstName", a space string, and"$lastName"to join names with a space.Step 2: Calculate age using $subtract
SubtractbirthYearfield from 2024 using$subtract. Field references need$.Step 3: Check each option
{ $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] }, age: { $subtract: [2024, "$birthYear"] }, _id: 0 } } correctly uses$concatwith space and$subtractwith field references. { $project: { fullName: "$firstName $lastName", age: 2024 - "$birthYear", _id: 0 } } uses invalid string concatenation and arithmetic. { $project: { fullName: { $concat: ["firstName", " ", "lastName"] }, age: { $subtract: [2024, "birthYear"] }, _id: 0 } } misses$on fields. { $project: { fullName: { $concat: ["$firstName", "$lastName"] }, age: { $subtract: ["birthYear", 2024] }, _id: 0 } } misses space and reverses subtraction.Final Answer:
{ $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] }, age: { $subtract: [2024, "$birthYear"] }, _id: 0 } } -> Option AQuick Check:
Use $concat with space and $subtract with $field [OK]
Hint: Use $concat with spaces and $subtract with $field for calculations [OK]
Common Mistakes:
- Forgetting $ before field names
- Concatenating fields without spaces
- Subtracting in wrong order
- Using string expressions instead of operators
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
