In the following Mongodb query I’m getting “undefined” in my $divide expression for “correct” and “guessCount”. How do I correct this? My intent is to return a percentage labeled as “accuracy” that is the result of dividing the sum of correct guesses divided by the number of guesses. This should be pretty clear from the provided code.
guessCollection.aggregate( { $group :
{ _id : "$imageFileName",
correct : { $sum : "$correct" },
guessCount: {$sum: 1 },
accuracy: {$divide: [correct, guessCount]}, //guess and guessCount are undefined
} },
{ $match : {guessCount : { $gte : 50 }, user: user, language: language } } ,
{ $sort: { guessCount: -1 } }, callback)
$divideis a$projectoperator, not a$groupoperator, so you need to do this instead:Your next problem will likely be that you’re referencing the
languageanduserfields in your$matchbecause you’re not including those in your$groupso you’ll probably want to move that part to the beginning of your pipeline like this: