Serve Laurijssen
Serve Laurijssen

Reputation: 9753

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" } } }])

Upvotes: 0

Views: 94

Answers (1)

ray
ray

Reputation: 15256

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.

Upvotes: 1

Related Questions