我有数据
{"id" :1,"win":100},
{"id" :1,"win":150},
{"id" :1,"win":10},
{"id" :1,"win":0},
{"id" :2,"win":100},
{"id" :2,"win":0},
{"id" :3,"win":100},
{"id" :3,"win":200},
我需要找到每个id的胜率; 预期产出
id: 1 winper:75
id: 2 winper:50
id: 1 winper:100
totalwin is no. of greatethan zero win
totalnotwin is no. equal to zero win
我得到了以下查询
db.winn.aggregate([
{
$group: { _id: "$id",
totalnotwon: {
$sum:
{ $cond: [ { $lte: [ "$win", 0 ] }, 1, 0] }
}
,
totalwin: {
$sum:
{ $cond: [ { $gt: [ "$win", 0 ] }, 1, 0] }
}
}
}
],function (err, result) {
console.log(result);
res.json(result);
});
});
我得到了结果
as id totlwon totlanotwon 1 3 1 2 1 1 3 2 0
我需要计算胜利的百分比 预期 id totlwon totlanotwon% 1 3 1 75 2 1 1 50 3 2 0 100
win%logic(100 /(totlwon + totalnotwon))* totalwon
答案 0 :(得分:1)
请尝试此查询,它可能会根据您的公式给出结果:
(100/(totalwon+totalnotwon))*totalwon
查询:
db.demo.aggregate([
{
$group: {
_id: '$id',
total: { $sum: '$win' },
totalnotwon: {
$sum: { $cond: [{ $lte: ['$win', 0] }, 1, 0] },
},
totalwon: {
$sum: { $cond: [{ $gt: ['$win', 0] }, 1, 0] },
},
total: { $sum: NumberInt(1) },
},
},
{
$project: {
result: {
$floor:{$multiply:[{ $divide:[100,'$total']},'$totalwon']}
},
},
},
]);