What is the purpose of the $project stage in a MongoDB aggregation pipeline?
The $project stage is used to shape the output documents by including, excluding, or adding new fields. It controls which fields appear in the final result.
Click to reveal answer
beginner
How do you exclude a field named password using $project?
Set the field to 0 in $project: { password: 0 } excludes the password field from the output.
Click to reveal answer
intermediate
How can you rename a field firstName to name using $project?
Use the original field as the value for the new field: { name: "$firstName" } creates a new field name with the value from firstName.
Click to reveal answer
intermediate
Can you add a new field with a computed value in $project? Give an example.
Yes. For example, to add a field fullName by combining firstName and lastName: { fullName: { $concat: ["$firstName", " ", "$lastName"] } }
Click to reveal answer
advanced
What happens if you include one field with 1 and exclude another with 0 in the same $project stage?
MongoDB does not allow mixing inclusion (1) and exclusion (0) except for the _id field. You must choose either to include fields or exclude fields, but not both.
Click to reveal answer
What does { age: 1 } mean inside a $project stage?
ACreate a new field named <code>age</code>
BExclude the <code>age</code> field from the output
CRename the <code>age</code> field
DInclude the <code>age</code> field in the output
✗ Incorrect
Setting a field to 1 in $project means to include that field in the output documents.
How do you exclude the password field in $project?
A{ password: false }
B{ password: 1 }
C{ password: 0 }
D{ password: null }
✗ Incorrect
Setting a field to 0 in $project excludes it from the output.
Which of the following is a valid way to add a new field fullName by combining firstName and lastName?
C. Field name "age" should be prefixed with $ to reference the field.
D. The field fullName cannot be renamed.
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
$multiply is valid in $project. Excluding _id is allowed. Renaming fields is allowed.
Final Answer:
Field name "age" should be prefixed with $ to reference the field. -> Option C
Quick 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?