mongoose/mongodb 查询多重排序 [英] mongoose/mongodb query multiple sort
问题描述
我对 mongodb 很陌生.我设法获得了仅基于 1 个参数的简单排序的基本概念.如果有超过 2 个排序参数怎么办.例如,在由具有属性 totalCuttingTime
和 favorited
的木工项目组成的数据库中.
i'm quite new to mongodb. i manage to get a basic idea of a simple sort based only 1 parameter. what if there are more than 2 sort parameters. for instance, in a database made up of woodworking projects that have attributes totalCuttingTime
and favorited
.
以下是否是正确的 mongoose/mongodb 函数,用于查找具有 least
totalCuttingTime 的项目列表,并根据 highest
favoriteCounts 排序到最低.
Is the following a correct mongoose/mongodb function to find a list of projects that have the least
totalCuttingTime and order in according to highest
favoriteCounts to lowest.
var ProjectModel= mongoose.model('Project', schema);
exports.getMinCuttingTime = function(number, callback){
var leastCutTimeResult = ProjectModel.find().sort({totalCuttingTime: 1}).select({_id: 1}).limit(number).exec(
function(err, projects) {
callback(null, projects)
}
);
var result = leastCutTimeResult.find().sort({favoriteCount: -1}).select({_id: 1}).limit(number).exec(
function(err, projects) {
callback(null, projects)
}
);
return result;
}
推荐答案
您需要将两个 sort
项放在一个对象中:
You need to put both sort
terms into one object:
exports.getMinCuttingTime = function(number, callback){
ProjectModel.find()
.sort({totalCuttingTime: 1, favoriteCount: -1})
.select({_id: 1})
.limit(number)
.exec(
function(err, projects) {
callback(null, projects)
}
);
};
值得注意的是,Node.js 所基于的 ECMA-262 标准并没有规定维护对象的属性顺序,它只是匹配插入顺序的事实上的标准.为了消除任何疑问,您可以使用数组代替:
It's worth noting that the ECMA-262 standard on which Node.js is based doesn't specify that an object's property order is maintained, and it's only a de facto standard to match insertion order. To eliminate any doubt, you can use an array instead:
.sort([['totalCuttingTime', 1], ['favoriteCount', -1]])
这篇关于mongoose/mongodb 查询多重排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!