在下面的Mongodb查询中,我的$ divide表达式中的“undefined”为“correct”和“guessCount”。我该如何纠正?我的目的是返回标记为“准确度”的百分比,这是将正确猜测的总和除以猜测数的结果。从提供的代码中可以清楚地看出这一点。
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)
答案 0 :(得分:3)
$divide
是$project
运算符,而不是$group
运算符,因此您需要执行此操作:
guessCollection.aggregate( { $group :
{ _id : "$imageFileName",
correct : { $sum : "$correct" },
guessCount: {$sum: 1 }
} },
{ $match : {guessCount : { $gte : 50 }, user: user, language: language } } ,
{ $project : {
correct: 1,
guessCount: 1,
accuracy: {$divide: ['$correct', '$guessCount']}
}},
{ $sort: { guessCount: -1 } }, callback)
您的下一个问题可能是,您引用了language
中的user
和$match
字段,因为您未在$group
中添加这些字段,因此您我可能希望将这部分移动到您的管道的开头,如下所示:
guessCollection.aggregate(
{ $match : { user: user, language: language } } ,
{ $group : {
_id : "$imageFileName",
correct : { $sum : "$correct" },
guessCount: {$sum: 1 }
} },
{ $match : {guessCount : { $gte : 50 } } } ,
{ $project : {
correct: 1,
guessCount: 1,
accuracy: {$divide: ['$correct', '$guessCount']}
}},
{ $sort: { guessCount: -1 } }, callback)