Bird
Raised Fist0
MongoDBquery~10 mins

$project stage for shaping output in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - $project stage for shaping output
Input Documents
↓
$project Stage
↓
Select Fields
↓
Rename or Create Fields
↓
Output Documents with New Shape
The $project stage takes input documents, selects or reshapes fields, and outputs documents with the new structure.
Execution Sample
MongoDB
db.orders.aggregate([
  { $project: { item: 1, total: { $multiply: ["$price", "$quantity"] } } }
])
This pipeline reshapes each order document to keep 'item' and add a new 'total' field calculated by multiplying price and quantity.
Execution Table
StepInput DocumentActionProjected FieldsOutput Document
1{"item": "apple", "price": 2, "quantity": 5, "category": "fruit"}Keep 'item', compute 'total' = price * quantity{"item": "apple", "total": 10}{"item": "apple", "total": 10}
2{"item": "banana", "price": 1, "quantity": 10, "category": "fruit"}Keep 'item', compute 'total' = price * quantity{"item": "banana", "total": 10}{"item": "banana", "total": 10}
3{"item": "carrot", "price": 3, "quantity": 4, "category": "vegetable"}Keep 'item', compute 'total' = price * quantity{"item": "carrot", "total": 12}{"item": "carrot", "total": 12}
4No more documentsEnd of pipelineN/APipeline ends
💡 All input documents processed, pipeline ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
Input DocumentN/A{"item": "apple", "price": 2, "quantity": 5, "category": "fruit"}{"item": "banana", "price": 1, "quantity": 10, "category": "fruit"}{"item": "carrot", "price": 3, "quantity": 4, "category": "vegetable"}No more documents
Projected FieldsN/A{"item": "apple", "total": 10}{"item": "banana", "total": 10}{"item": "carrot", "total": 12}N/A
Output DocumentN/A{"item": "apple", "total": 10}{"item": "banana", "total": 10}{"item": "carrot", "total": 12}Pipeline ends
Key Moments - 2 Insights
Why does the output document only have 'item' and 'total' fields, not 'price' or 'quantity'?
Because the $project stage explicitly includes only 'item' and the computed 'total' field, all other fields are excluded by default as shown in execution_table rows 1-3.
How is the 'total' field calculated in each output document?
The 'total' field is computed by multiplying the 'price' and 'quantity' fields from the input document, as seen in the Action column of execution_table rows 1-3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2. What is the value of the 'total' field in the output document?
A10
B1
C11
D0
💡 Hint
Check the 'Projected Fields' column at Step 2 in the execution_table.
At which step does the pipeline finish processing all documents?
AStep 3
BStep 4
CStep 2
DStep 1
💡 Hint
Look for the row where 'No more documents' is in the Input Document column.
If we added 'category: 1' to the $project stage, what would change in the output documents?
AThe output documents would include the 'category' field as well.
BThe 'total' field would be removed.
CThe input documents would change.
DNothing would change.
💡 Hint
Refer to how $project controls which fields appear in output documents in the execution_table.
Concept Snapshot
$project stage reshapes documents in aggregation.
Specify fields to keep with 1, exclude others.
Create new fields with expressions.
Output documents have only projected fields.
Useful for selecting, renaming, or computing fields.
Full Transcript
The $project stage in MongoDB aggregation takes each input document and reshapes it by selecting specific fields to keep or exclude. It can also create new fields using expressions like multiplication. In the example, the pipeline keeps the 'item' field and adds a new 'total' field calculated by multiplying 'price' and 'quantity'. Each input document is processed step-by-step, producing output documents with only the projected fields. The pipeline ends after all documents are processed.

Practice

(1/5)
1. What does the $project stage do in a MongoDB aggregation pipeline?
easy
A. It filters documents based on conditions.
B. It shapes the output by selecting, renaming, or creating fields.
C. It sorts the documents in ascending or descending order.
D. It groups documents by a specified key.

Solution

  1. Step 1: Understand the purpose of $project

    The $project stage is used to control which fields appear in the output documents and how they are shaped.
  2. Step 2: Compare with other stages

    Filtering is done by $match, sorting by $sort, and grouping by $group. So $project is for shaping output fields.
  3. Final Answer:

    It shapes the output by selecting, renaming, or creating fields. -> Option B
  4. Quick Check:

    $project shapes 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
A. { $project: { name: 1, age: 1 } }
B. { $project: { name: 0, age: 0 } }
C. { $project: { name: true, age: true } }
D. { $project: { name: 'include', age: 'include' } }

Solution

  1. Step 1: Recall $project syntax for inclusion

    To include fields, set them to 1. To exclude, set to 0. Boolean or strings are invalid.
  2. Step 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.
  3. Final Answer:

    { $project: { name: 1, age: 1 } } -> Option A
  4. Quick 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:
{ "name": "Alice", "age": 25, "city": "NY" }

What will be the output of this aggregation?
[{ $project: { fullName: "$name", ageInMonths: { $multiply: ["$age", 12] }, _id: 0 } }]
medium
A. [{ "fullName": "Alice", "ageInMonths": 25 }]
B. [{ "name": "Alice", "ageInMonths": 300 }]
C. [{ "fullName": "Alice", "age": 25 }]
D. [{ "fullName": "Alice", "ageInMonths": 300 }]

Solution

  1. Step 1: Understand field renaming and calculation

    The fullName field is created by copying name. The ageInMonths is calculated by multiplying age by 12 (25*12=300). The _id is excluded.
  2. Step 2: Check output fields

    Output has fullName with "Alice" and ageInMonths with 300. No name or age fields remain.
  3. Final Answer:

    [{ "fullName": "Alice", "ageInMonths": 300 }] -> Option D
  4. Quick 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
A. The _id field cannot be excluded.
B. Cannot use $multiply inside $project.
C. Field name "age" should be prefixed with $ to reference the field.
D. The field fullName cannot be renamed.

Solution

  1. Step 1: Check field references in expressions

    In MongoDB aggregation, to reference a field inside expressions, prefix with $. Here, "age" is missing $.
  2. Step 2: Validate other parts

    $multiply is valid in $project. Excluding _id is allowed. Renaming fields is allowed.
  3. Final Answer:

    Field name "age" should be prefixed with $ to reference the field. -> Option C
  4. 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?
hard
A. { $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] }, age: { $subtract: [2024, "$birthYear"] }, _id: 0 } }
B. { $project: { fullName: "$firstName $lastName", age: 2024 - "$birthYear", _id: 0 } }
C. { $project: { fullName: { $concat: ["firstName", " ", "lastName"] }, age: { $subtract: [2024, "birthYear"] }, _id: 0 } }
D. { $project: { fullName: { $concat: ["$firstName", "$lastName"] }, age: { $subtract: ["birthYear", 2024] }, _id: 0 } }

Solution

  1. Step 1: Build fullName using $concat with spaces

    Use $concat with "$firstName", a space string, and "$lastName" to join names with a space.
  2. Step 2: Calculate age using $subtract

    Subtract birthYear field from 2024 using $subtract. Field references need $.
  3. Step 3: Check each option

    { $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] }, age: { $subtract: [2024, "$birthYear"] }, _id: 0 } } correctly uses $concat with space and $subtract with 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.
  4. Final Answer:

    { $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] }, age: { $subtract: [2024, "$birthYear"] }, _id: 0 } } -> Option A
  5. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard