MongoDB aggregation $divide computed fields

前端 未结 1 1993
小鲜肉
小鲜肉 2021-01-01 20:25

I am trying to compute a percentage in a MongoDB query based on computed fields - not sure if this is possible or not. What I\'d like to be able to do is calculate the fail

相关标签:
1条回答
  • 2021-01-01 21:25

    You almost got it. Only change that would be required is that you'll have to compute the FailPercent in an additional project phase, because the total is only available after the completion of the group phase. Try this:

    db.foo.aggregate([    
        { $match: { "data.buildResult" : { $ne : null } } },
        { $group: {          
            _id: {              
                month: { $month: "$time" },             
                day: { $dayOfMonth: "$time" },             
                year: { $year: "$time" },                       
            },         
            Aborted: { $sum: { $cond :  [{ $eq : ["$data.buildResult", "ABORTED"]}, 1, 0]} },
            Failure: { $sum: { $cond :  [{ $eq : ["$data.buildResult", "FAILURE"]}, 1, 0]} },
            Unstable: { $sum: { $cond : [{ $eq : ["$data.buildResult", "UNSTABLE"]}, 1, 0]} },
            Success: { $sum: { $cond :  [{ $eq : ["$data.buildResult", "SUCCESS"]}, 1, 0]} },
            Total: { $sum: 1 }
        } }, 
        {$project:{Aborted:1, Failure:1, Unstable:1, Success:1, Total:1, FailPercent: { $divide: [ "$Failure", "$Total" ]}}},
        { $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1 } } 
    ])
    
    0 讨论(0)
提交回复
热议问题