0

enter image description here

I Want to count "winStatus" 3 times by condition LOSS, Win and Pending.

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);
    });

how this can be done ?

coder_B
  • 110
  • 11

1 Answers1

0

Add $cond in group stage as

 {$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);
    });
coder_B
  • 110
  • 11
sushant mehta
  • 1,244
  • 1
  • 7
  • 13
  • giving error "MongoError: unknown group operator '$cond'" – coder_B Sep 26 '19 at 08:04
  • 3
    Add $sum before $cond. You will get the correct result. "winCount": { "$sum": { "$cond": { "$eq": [ "$winStatus", "$Win" ] }, 1, 0 } }, – kRiZ Sep 26 '19 at 08:12
  • winCount: { "$sum": { $cond: { if: { $eq: ['$winStatus', 'Win'] }, then: 1, else: 0 } } }, this gave me result thank you :) – coder_B Sep 26 '19 at 08:21