KeplerGrid guide

Sum MongoDB array items with $reduce

Calculate one order total from its embedded line items. Return a zero total for empty or missing arrays.

Load the practice collection

Run once in mongosh against a development instance with an empty lineOrders practice collection.

const lab = db.getSiblingDB("keplergrid_practice")
lab.lineOrders.insertMany([
  { _id: "ORD-101", lines: [{ qty: 2, unitCents: 499 }, { qty: 1, unitCents: 250 }] },
  { _id: "ORD-102", lines: [] },
  { _id: "ORD-103" }
])

In KeplerGrid, open keplergrid_practice.lineOrders with a Read only connection.

Accumulate line totals in integer cents

Paste into Aggregation → JSON and choose Run pipeline.

[
  { "$set": { "totalCents": {
    "$reduce": {
      "input": { "$ifNull": ["$lines", []] },
      "initialValue": 0,
      "in": { "$add": [
        "$$value", { "$multiply": ["$$this.qty", "$$this.unitCents"] }
      ] }
    }
  } } },
  { "$sort": { "_id": 1 } }
]

$$value holds the running total and $$this is the current line. The results are 1248, 0, and 0 cents. An empty array retains initialValue and $ifNull supplies an empty array for the missing field.

Check the input before trusting the totals

Open Stages and inspect $set. Compare the line items under Input with totalCents under Output. The calculation assumes a real array and numeric item values. Audit malformed records separately.

See how to calculate a running total across orders or revisit the related KeplerGrid walkthrough.