将Mongo Aggregate函数与$ Divide表达式一起使用时的未定义变量

时间:2012-12-15 20:29:49

标签: mongodb

在下面的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)

1 个答案:

答案 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)