如何使用group-by和条件来计算mongo db中的多个字段

时间:2019-09-26 07:59:53

标签: node.js mongodb mongoose

enter image description here

我想按条件“丢失”,“赢”和“未决”对“ winStatus”计数3次。

AtomicSequence

这怎么办?

1 个答案:

答案 0 :(得分:0)

在小组赛阶段将$ cond添加为

 {$group: {
 gameBids.aggregate([
        { 
            $group : { 
                _id: "$userId",
                countBids: { $sum: 1 },
                winCount: {
                    "$sum": {
                        $cond: {
                            if: { $eq: ['$winStatus', 'Win'] }, then: 1, else: 0
                        }
                    }
                },               
                loseCount: {
                    "$sum": {
                        $cond: {
                            if: { $eq: ['$winStatus', 'Loss'] }, then: 1, else: 0
                        }
                    }
                },
                pendingCount: {
                    "$sum": {
                        $cond: {
                            if: { $eq: ['$winStatus', 'Pending'] }, then: 1, else: 0
                        }
                    }
                },
                sumbiddingPoints:    { $sum: '$biddingPoints' },
                sumWinPoint         : { $sum: '$gameWinPoints'}
            }
        }
    ], function (error, group) {
            if (error) throw error;
            else res.json(group);
    });