如何在mongoose中进行排序?

238

我找不到关于排序修饰符的文档。唯一的线索在于单元测试中: spec.lib.query.js#L12

writer.limit(5).sort(['test', 1]).group('name')

但对我来说不起作用:

Post.find().sort(['updatedAt', 1]);

8
阅读此答案,获取最新回答。 - Francisco Presencia
21个回答

240
在Mongoose中,可以通过以下任一方式进行排序:
    Post.find({}).sort('test').exec(function(err, docs) { ... });
    Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
    Post.find({}).sort({test: 1}).exec(function(err, docs) { ... });
    Post.find({}, null, {sort: {date: 1}}, function(err, docs) { ... });

8
这几乎是与Francisco Presencia提供的答案直接复制。不幸的是,得票最高的答案已经过时且过于冗长。 - iwein
4
截至今天这个说法不太准确。{sort: [['date', 1]]}将不能正常工作,但是.sort([['date', -1]])可以正常工作。请参考这个回答:https://dev59.com/Dm025IYBdhLWcg3wvIq2#15081087 - steampowered
@steampowered 谢谢,我会进行编辑,如果我有错误的话,请随时告诉我或者进行修改。 - iwein
4
愿意看到一些关于结果的注释,特别是关于1-1值的含义,而不是只有4行代码,没有太多上下文。 - Philipp

162

以下是我在mongoose 2.3.0中让排序工作的方法 :)

// Find First 10 News Items
News.find({
    deal_id:deal._id // Search Filters
},
['type','date_added'], // Columns to Return
{
    skip:0, // Starting Row
    limit:10, // Ending Row
    sort:{
        date_added: -1 //Sort by Date Added DESC
    }
},
function(err,allNews){
    socket.emit('news-load', allNews); // Do something with the array of 10 objects
})

8
在Mongoose 3中,您不能再使用Array进行字段选择 - 必须使用StringObject - Philipp Kyeck
5
顺便说一下,如果你想要所有字段,你可以在那个部分中只输入“null”(至少在3.8版本中是这样)。 - MalcolmOcean

107

截至Mongoose 3.8.x版本:

model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });

位置:

criteria 可以是 ascdescascendingdescending1-1

注:请使用引号或双引号

使用 "asc""desc""ascending""descending"1-1


非常感谢,它有效了! - undefined

78

更新:

Post.find().sort({'updatedAt': -1}).all((posts) => {
  // do something with the array of posts
});
尝试:
Post.find().sort([['updatedAt', 'descending']]).all((posts) => {
  // do something with the array of posts
});

13
在最新的Mongoose(2.4.10)中,它是.sort("updatedAt", -1) - Marcel Jackwerth
45
在更新的Mongoose版本(3.5.6-pre,但我相信对于所有3.x版本都是有效的),使用.sort({updatedAt: -1}).sort('-updatedAt')可以进行排序。 - Andreas Hultgren
2
那么你应该使用 exec(function (posts) {… 而不是 all - Buzut
我在Mongoose 4.6.5中遇到了all() must be used after where() when called with these arguments的错误。 - Dam Fa
我在Node.js中使用它,如下所示:Post.find().sort({updatedAt: -1}).all((posts) => { - dipakbari4

50

Mongoose v5.x.x

按升序排序

Post.find({}).sort('field').exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'asc' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'ascending' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 1 }).exec(function(err, docs) { ... });

Post.find({}, null, {sort: { field : 'asc' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 'ascending' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 1 }}), function(err, docs) { ... });

按照降序排序

Post.find({}).sort('-field').exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'desc' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'descending' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: -1 }).exec(function(err, docs) { ... });


Post.find({}, null, {sort: { field : 'desc' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 'descending' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : -1 }}), function(err, docs) { ... });

详情请参考:https://mongoosejs.com/docs/api.html#query_Query-sort


正如 @Sunny Sultan 指出的,所有的 Post.find({}, null, {sort: '-field'}, function(err, docs) { ... }); 可以用于降序查询,而 Post.find({}, null, {sort: 'field'}, function(err, docs) { ... }); 则可以用于升序查询。事实上,由于我将字段和排序顺序作为 HTTP 查询参数传递,将它们组合成一个字符串并使用这种方式对我的数据库查询进行排序是唯一的选择。 - Vincenzo

24

更新

如果这篇文章让人感到困惑,可以查看mongoose手册中的查找文档查询工作原理,那里有更好的解释。如果你想使用流畅的API,可以通过不提供find()方法的回调来获得一个查询对象,否则你可以按照我下面的说明来指定参数。

原始内容

根据模型文档中对model对象的描述,对于版本2.4.1,它可以起作用的方式如下:

Post.find({search-spec}, [return field array], {options}, callback)

搜索规范(search spec)需要一个对象,但你可以传递null或一个空对象。

第二个参数是字段列表,作为字符串数组。例如,你应该使用['field','field2']null

第三个参数是选项,作为一个对象,其中包括对结果集进行排序的能力。你将使用{ sort: { field: direction } },其中field是字段名 test 的字符串(在你的情况下),而direction则是一个数字,其中1表示升序,-1表示降序。

最后一个参数(callback)是回调函数,用于接收查询返回的文档集合。

Model.find()实现(在此版本中)使用滑动分配属性来处理可选参数(这就是让我困惑的地方!):

Model.find = function find (conditions, fields, options, callback) {
  if ('function' == typeof conditions) {
    callback = conditions;
    conditions = {};
    fields = null;
    options = null;
  } else if ('function' == typeof fields) {
    callback = fields;
    fields = null;
    options = null;
  } else if ('function' == typeof options) {
    callback = options;
    options = null;
  }

  var query = new Query(conditions, options).select(fields).bind(this, 'find');

  if ('undefined' === typeof callback)
    return query;

  this._applyNamedScope(query);
  return query.find(callback);
};

HTH


为了投影:我们需要提供一个包含以空格分隔的列名的字符串。 - maddy

18

您可以通过以下方式对查询结果进行排序:

Post.find().sort({createdAt: "descending"});


12

以下是我如何在 mongoose.js 2.0.4 中使用排序的方法

var query = EmailModel.find({domain:"gmail.com"});
query.sort('priority', 1);
query.exec(function(error, docs){
  //...
});

11
在Mongoose 4中使用查询构建器接口进行链接。
// Build up a query using chaining syntax. Since no callback is passed this will create an instance of Query.
var query = Person.
    find({ occupation: /host/ }).
    where('name.last').equals('Ghost'). // find each Person with a last name matching 'Ghost'
    where('age').gt(17).lt(66).
    where('likes').in(['vaporizing', 'talking']).
    limit(10).
    sort('-occupation'). // sort by occupation in decreasing order
    select('name occupation'); // selecting the `name` and `occupation` fields


// Excute the query at a later time.
query.exec(function (err, person) {
    if (err) return handleError(err);
    console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host
})

有关查询的更多信息,请参见文档


7
app.get('/getting',function(req,res){
    Blog.find({}).limit(4).skip(2).sort({age:-1}).then((resu)=>{
        res.send(resu);
        console.log(resu)
        // console.log(result)
    })
})

输出

[ { _id: 5c2eec3b8d6e5c20ed2f040e, name: 'e', age: 5, __v: 0 },
  { _id: 5c2eec0c8d6e5c20ed2f040d, name: 'd', age: 4, __v: 0 },
  { _id: 5c2eec048d6e5c20ed2f040c, name: 'c', age: 3, __v: 0 },
  { _id: 5c2eebf48d6e5c20ed2f040b, name: 'b', age: 2, __v: 0 } ]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接