0
0
MongoDBquery~30 mins

$addFields for computed fields in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$addFields for computed fields in MongoDB
📖 Scenario: You are managing a small online store database. Each product document has a price and quantity field. You want to add a new field that shows the total value of each product's stock (price multiplied by quantity).
🎯 Goal: Build a MongoDB aggregation pipeline that uses $addFields to add a computed field called totalValue to each product document. This field should be the product of price and quantity.
📋 What You'll Learn
Create a collection called products with three documents having exact fields and values.
Add a variable called pipeline that holds an array for the aggregation pipeline.
Use $addFields in the pipeline to add a new field totalValue computed as price * quantity.
Complete the aggregation command using db.products.aggregate(pipeline).
💡 Why This Matters
🌍 Real World
Stores often need to calculate total stock value for inventory management and reporting.
💼 Career
Understanding aggregation pipelines and computed fields is essential for database developers and data analysts working with MongoDB.
Progress0 / 4 steps
1
Create the products collection with sample documents
Create a variable called products that is an array with these three exact documents: { _id: 1, name: 'Pen', price: 1.5, quantity: 100 }, { _id: 2, name: 'Notebook', price: 3, quantity: 200 }, and { _id: 3, name: 'Eraser', price: 0.5, quantity: 300 }.
MongoDB
Need a hint?

Use a list of dictionaries with exact keys and values as shown.

2
Create the aggregation pipeline variable
Create a variable called pipeline and set it to an empty array [] to prepare for the aggregation stages.
MongoDB
Need a hint?

Just create a variable named pipeline and assign an empty list [].

3
Add the $addFields stage to compute totalValue
Add a dictionary to the pipeline array that uses $addFields to add a new field called totalValue. This field should be computed as the multiplication of price and quantity using { $multiply: ["$price", "$quantity"] }.
MongoDB
Need a hint?

Use { '$addFields': { 'totalValue': { '$multiply': ["$price", "$quantity"] } } } inside the pipeline list.

4
Complete the aggregation command
Write a line that calls db.products.aggregate(pipeline) to run the aggregation pipeline on the products collection.
MongoDB
Need a hint?

Use db.products.aggregate(pipeline) exactly to run the pipeline.