我有交易文件,如:
{code: 'BUY001', timestamp: ISODate("..."), type: 'buy', qty: 500},
{code: 'SELL001', timestamp: ISODate("..."), type: 'sell', qty: 10},
{code: 'SELL002', timestamp: ISODate("..."), type: 'sell', qty: 80},
{code: 'BUY002', timestamp: ISODate("..."), type: 'buy', qty: 50}
我想总结这里列出的所有卖/买交易,按时间戳排序以获得我项目的最终结果。这是我的传统解决方案:
db.transaction.find().sort({timestamp: 1}, function(err, reply){
var total = 0;
for(var i = 0; i < reply.length; i++){
if(reply[i].type === 'buy') total += reply[i].qty;
else if(reply[i].type === 'sell') total -= reply[i].qty;
}
return console.log(total); // TOTAL IS THE RESULT
})
我可以使用上面函数的聚合等价物吗?有什么建议? 谢谢
答案 0 :(得分:0)
您可以使用带$sum
操作的聚合来查找每种类型的总计。
output = db.test.aggregate([
{
'$group' : {
'_id' : '$type',
'total' : {$sum : '$qty'}
}
}
]).toArray()
然后你会得到如下结果。
[
{
"_id" : "sell",
"total" : 90
},
{
"_id" : "buy",
"total" : 550
}
]
使用这些数组,您可以使用
找到所需的输出output[1].total - output[0].total
答案 1 :(得分:0)
db.transaction.aggregate([
/* Group all documents.
Sum all type matching 'buy' and store in a field called buy.
Sum all type matching 'sell' and store in a field called sell.
*/
{$group:{
'_id':null,
'buy':{$sum:{
$cond:[
{$eq:["$type", "buy"]},
"$qty",
0 ]
}
},
'sell':{$sum:{
$cond:[
{$eq:["$type", "sell"]},
"$qty",
0 ]
}
}
}
},
/* Subtract buy field with sell field. */
{$project: {
"total": {$subtract:["$buy", "$sell"]}
}
}
]);
使用您提供的4份文件,结果应为460.