0
0
MongoDBquery~5 mins

$project stage for shaping output in MongoDB - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
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: <br>{ 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: <br>{ 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:<br>{ 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
How do you exclude the password field in $project?
A{ password: false }
B{ password: 1 }
C{ password: 0 }
D{ password: null }
Which of the following is a valid way to add a new field fullName by combining firstName and lastName?
A{ fullName: { $concat: ["$firstName", " ", "$lastName"] } }
B{ fullName: "$firstName" & "$lastName" }
C{ fullName: "$firstName" + "$lastName" }
D{ fullName: "$firstName $lastName" }
What is the default behavior of _id in $project if not specified?
AIt is excluded by default
BIt is included by default
CIt causes an error
DIt is renamed to <code>id</code>
Is this $project valid? { name: 1, age: 0 }
ANo, mixing inclusion and exclusion is not allowed
BYes, it includes <code>name</code> and excludes <code>age</code>
CYes, but only if <code>_id</code> is excluded
DNo, fields must be set to true or false
Explain how the $project stage shapes the output in a MongoDB aggregation pipeline.
Think about how you can choose which data to see and how it looks.
You got /4 concepts.
    Describe the rules about mixing field inclusion and exclusion in the $project stage.
    Remember the special case for the _id field.
    You got /3 concepts.