0
0
MongoDBquery~3 mins

Why $addFields for computed fields in MongoDB? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could add new insights to your data instantly, without any manual work?

The Scenario

Imagine you have a big list of sales records in a spreadsheet. You want to add a new column that shows the total price by multiplying quantity and price per item. Doing this by hand for hundreds or thousands of rows is tiring and slow.

The Problem

Manually calculating and adding new columns in a spreadsheet or text file is error-prone and takes a lot of time. If the data changes, you must redo all calculations. It's easy to make mistakes and hard to keep everything updated.

The Solution

The $addFields stage in MongoDB lets you add new fields to your data automatically by computing values from existing fields. This means you can create new information on the fly without changing the original data, saving time and avoiding errors.

Before vs After
Before
For each record: total = quantity * price_per_item; add total as new column
After
db.collection.aggregate([{ $addFields: { total: { $multiply: ["$quantity", "$price_per_item"] } } }])
What It Enables

It enables you to enrich your data dynamically with new computed fields, making your queries smarter and your reports more insightful.

Real Life Example

A store manager can quickly see total sales per item by multiplying quantity sold by unit price, all within the database query, without extra manual work.

Key Takeaways

Manual calculations are slow and error-prone.

$addFields computes new fields automatically in queries.

This makes data analysis faster, easier, and more reliable.