与子文档项目的计算和相加

我有发票模型如下

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

我需要计算项目总价或销售价格 – 折扣。

我看到了$sum操作符,但找不到与item._id

如果你正在寻找一个数组的“内部”属性,那么你总是需要$unwind 。 如果您需要在通过$sum累计之前应用“math”,则使用math运算符 。 比如在这种情况下$subtract

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

当然,假定itemDetails.item实际上是不同发票中的项目通用的。