user2473015
user2473015

Reputation: 1442

Sum with Calculation from Sub-Document items

I have invoice Model as following

{
...

"itemDetails": [
            {
                "item":  "593a1a01bbb00000043d9a4c",
                "purchasingPrice": 100,
                "sellingPrice": 150,
                "qty": 200,
                "_id": "59c39c2a5149560004173a05",
                "discount": 0
            }
        ],
        "payments": [],
...

}

I need to calculate item-vice total sum or selling price - discount.

I saw $sum operator but couldn't find a way to group with item._id

Upvotes: 1

Views: 66

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151200

If you are looking to get a total grouped by a property "inside" an array, then you always need $unwind. If you need to apply "math" before accumulating via $sum, then use the math operators. Such as $subtract in this case:

Model.aggregate([
  { "$unwind": "$itemDetails" },
  { "$group": {
    "_id": "$itemDetails.item",
    "salePrice": { 
      "$sum": {
        "$subtract": [ "$itemDetails.sellingPrice", "$itemDetails.discount" ]
      }
    }
  }}
])

Presuming of course that itemDetails.item is actually common to the items in different invoices.

Upvotes: 2

Related Questions