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 ?

0

1 Answer 1

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);
    });
Sign up to request clarification or add additional context in comments.

3 Comments

giving error "MongoError: unknown group operator '$cond'"
Add $sum before $cond. You will get the correct result. "winCount": { "$sum": { "$cond": { "$eq": [ "$winStatus", "$Win" ] }, 1, 0 } },
winCount: { "$sum": { $cond: { if: { $eq: ['$winStatus', 'Win'] }, then: 1, else: 0 } } }, this gave me result thank you :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.