mongoose / mongodb查询多种排序 [英] mongoose/mongodb query multiple sort

查看:169
本文介绍了mongoose / mongodb查询多种排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对mongodb很新。我设法只得到一个基于1参数的简单排序的基本概念。如果有超过2个排序参数怎么办?例如,在由木工项目组成的数据库中,该项目具有属性 totalCuttingTime 被收藏

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函数来查找具有最小 totalCuttingTime的项目列表,并按照<$ c顺序输入$ c>最高 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;
}


推荐答案

你需要把两者都放在一起code> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆