Search code examples
mongodbmongodb-query

getting sum of list in list of documents


Consider this mongo document, an order with an internal list of products with their counts:

{
  ordernumber: "1234"
  detail: [
    { "number": "987",
    "count": 10 },
    { "number": "654",
    "count": 5 }
  ]
}

How do we get the sum of all counts with mongodb shell? I always get zero for sum and dont know what to pass for _id.

db.preorders.aggregate([ { $match: {} }, { $group: { _id: "$_id", total: { $sum: "$detail.count" } } }])

Solution

  • You can do a $unwind first, then $group on null.

    db.collection.aggregate([
      {
        "$unwind": "$detail"
      },
      {
        "$group": {
          "_id": null,
          "total": {
            "$sum": "$detail.count"
          }
        }
      }
    ])
    

    Here is the Mongo Playground for your reference.