mongodb在用计数分组后获得获胜百分比

monogdb get the percentage of win after grouping with count

我有数据

{"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

请尝试这个查询,它可能会根据您的公式给出结果:

(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']}
      },
    },
  },
]);