$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