如何获得具有所有匹配logging的特定数字字段的总和

即时通讯使用与node.jsmongoose和我有交易模式和发票模型。 我想获得具有特定发票编号的所有logging。 即时通讯使用此查询来获得发票匹配的交易。

Transaction.find({invoice_id: invoiceId}) 

即时通讯logging在这种forms

 [ { "_id": "5795e3f4f4a0fb8c1dff20ad", "description": "This is a transcation", "invoice_id": "5795db00bfa9d366194a454d", "amount": 50 }, { "_id": "5795e3faf4a0fb8c1dff20ae", "description": "This is a transcation", "invoice_id": "5795db00bfa9d366194a454d", "amount": 100 } ] 

但问题是,我也想通过总和“金额”字段值在事务数组的每个对象的totalAmount。 我期望的结果是

 [ { "_id": "5795e3f4f4a0fb8c1dff20ad", "description": "This is a transcation", "invoice_id": "5795db00bfa9d366194a454d", "amount": 50 }, { "_id": "5795e3faf4a0fb8c1dff20ae", "description": "This is a transcation", "invoice_id": "5795db00bfa9d366194a454d", "amount": 100 }, { totalAmount: 150 } ] 

即时通讯使用$汇总函数的总和,但我不知道我的问题将如何解决这个。

你应该使用聚合和$组来达到这个目的

  Transaction.aggregate([{ $group: { _id:{ invoice_id:"$invoice_id" }, count: { $sum: 1 }, totalAmount: { $sum: "$amount" }, } }]).exec() 

这样,你最好使用mongodb的mapReduce函数。 这里是一个例子:

 var map = function() { emit(this.invoice_id, this.amount); }; var reduce = function(key, values) { var totalAmount = 0; for (var i + 0; i < values.length; i++) { totalAmount += values[i]; } return totalAmount; }; var res = db.mapReduce(map, reduce); 

如果您确实需要一张发票编号,请使用以下更新的地图function:

 var id = "1"; var map = function() { emit(id, this.amount); };