KeplerGrid guide

Calculate a field in MongoDB aggregation with $set

Use the aggregation stage $set to add a calculated field to every result. Multiplying an integer quantity by a BSON Decimal128 price keeps the result in Decimal128 in this example.

Multiply quantity by the stored price

Use the five synthetic orders from the $facet guide. In KeplerGrid, open keplergrid_reports.orders on a Read only connection. Select Aggregation → JSON, paste the pipeline, and choose Run pipeline.

[
  { "$sort": { "_id": 1 } },
  { "$set": {
    "lineTotal": { "$multiply": ["$quantity", "$unitPrice"] }
  } }
]

The strings "$quantity" and "$unitPrice" are references to fields on each order. $addFields is an alias for this aggregation stage. Use a new output field name such as lineTotal to keep both the source values and calculation visible in the result. A matching field name replaces that field’s value for the rest of the pipeline.

Verify the value and BSON type in KeplerGrid

Switch to Stages and select $set. Compare order O-101 in the Input and Output panels. The input price is { "$numberDecimal": "12.50" } and the quantity is 2. The output adds lineTotal with the value below.

{ "lineTotal": { "$numberDecimal": "25.00" } }

In the final JSON view, $numberDecimal identifies a BSON Decimal128 value. Store prices as Decimal128 when building this kind of calculation and verify their stored BSON type before applying it to real data. A price stored as a string needs explicit conversion before multiplication.

To verify the stored document, open Documents, apply the filter below, and choose Run. In the result, O-101 has its original quantity and price. lineTotal belongs to the aggregation result. A stage in a read-only aggregation calculates values at query time.

{ "_id": "O-101" }

Use the calculated value downstream

After $set, later stages can sort by lineTotal or sum it into a report. Use the $facet example to calculate counts and totals in one run. You can also export the aggregation results with the derived field included.

To compute a label from several conditions, classify documents with $switch.