多参数mongodb查询

时间:2012-11-28 15:45:46

标签: mongodb mongoose

找到价格最便宜的项目,评分数量最多且平均评分最高。这是正确的方法吗?

exports.getBestEconomicalProject = function(number, callback){  
    var result = ProjectModel.find().sort({averageCost: 1}, {ratingCount : -1}, {averageRating : -1}).select({_id: 1}).limit(number).exec(
            function(err, projects) {
                callback(null, projects)
            }
        );  
    return result;
}

1 个答案:

答案 0 :(得分:2)

您需要将所有sort个术语合并到一个对象中:

exports.getBestEconomicalProject = function(number, callback){  
    var result = ProjectModel.find()
        .sort({averageCost: 1, ratingCount : -1, averageRating : -1})
        .select({_id: 1})
        .limit(number)
        .exec(
            function(err, projects) {
                callback(null, projects)
            }
        );  
    return result;
}

或者使用sort的字符串格式:

exports.getBestEconomicalProject = function(number, callback){  
    var result = ProjectModel.find()
        .sort('averageCost -ratingCount -averageRating')
        .select({_id: 1})
        .limit(number)
        .exec(
            function(err, projects) {
                callback(null, projects)
            }
        );  
    return result;
}