【问题标题】:How to count Multiple Fields in mongo db Using Group-by with condition [duplicate]如何在 mongo db 中使用带有条件的 Group-by 来计算多个字段 [重复]
【发布时间】:2020-01-26 10:58:01
【问题描述】:

我想按条件 LOSS、Win 和 Pending 计算“winStatus”3 次。

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

如何做到这一点?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在小组赛中添加 $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);
        });
    

    【讨论】:

    • 给出错误“MongoError: unknown group operator '$cond'”
    • 在 $cond 之前添加 $sum。你会得到正确的结果。 "winCount": { "$sum": { "$cond": { "$eq": [ "$winStatus", "$Win" ] }, 1, 0 } },
    • winCount: { "$sum": { $cond: { if: { $eq: ['$winStatus', 'Win'] }, then: 1, else: 0 } } },这给了我结果谢谢:)
    猜你喜欢
    • 2016-12-14
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 2018-10-28
    • 1970-01-01
    • 2020-06-06
    相关资源
    最近更新 更多