如何获得特定数字字段与所有匹配记录的总和
问题描述:
即时使用mongoose与node.js,我有交易模型和发票模型。 我想获得具有特定发票编号的所有记录。 即时通讯使用此查询来获取发票的匹配交易。如何获得特定数字字段与所有匹配记录的总和
Transaction.find({invoice_id: invoiceId})
即时得到这种形式
[
{
"_id": "5795e3f4f4a0fb8c1dff20ad",
"description": "This is a transcation",
"invoice_id": "5795db00bfa9d366194a454d",
"amount": 50
},
{
"_id": "5795e3faf4a0fb8c1dff20ae",
"description": "This is a transcation",
"invoice_id": "5795db00bfa9d366194a454d",
"amount": 100
}
]
但问题的记录是,我也希望通过总和交易阵列的每个对象“量”字段中的值来获得总金额。 我期望的结果是使用
[
{
"_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
}
]
IM的聚合函数$总和,但我不知道我的问题将如何解决这个。
答
您应该总使用和$组为此
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);
如果你真的想要一个发票号,这里是更新的地图功能的使用方法:
var id = "1";
var map = function() { emit(id, this.amount); };
您还可以告诉我们您是如何使用'$ sum'聚合累加器运算符? – chridam