208

我找不到排序修饰符的文档。唯一的见解是单元测试: spec.lib.query.js#L12

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

但这对我不起作用:

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

20 回答 20

221

在 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) { ... });
于 2015-08-05T06:27:14.437 回答
158

这就是我在猫鼬 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
})
于 2011-10-10T07:15:43.327 回答
90

从 Mongoose 3.8.x 开始:

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

在哪里:

criteria可以是asc, desc, ascending, descending, 1, 或-1

注意:使用引号或双引号

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

于 2014-06-27T21:49:34.087 回答
71

更新:

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
});
于 2010-12-16T03:50:27.177 回答
44

猫鼬 v5.xx

按升序排序

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

于 2019-01-10T11:00:27.120 回答
24

更新

如果这让人们感到困惑,那么有一个更好的写法;查看mongoose 手册中的查找文档以及查询的工作原理。如果你想使用 fluent api,你可以通过不提供find()方法回调来获取查询对象,否则你可以指定参数,如下所述。

原来的

给定一个model对象,根据Model 上的文档,这就是它的工作方式2.4.1

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

需要一个对象,search spec但您可以传递null一个空对象。

第二个参数是作为字符串数组的字段列表,因此您可以提供['field','field2']or null

第三个参数是作为对象的选项,其中包括对结果集进行排序的能力。您将使用{ sort: { field: direction } }wherefield是字符串字段名test(在您的情况下),并且direction1升序和-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);
};

高温高压

于 2011-12-27T22:59:38.560 回答
12

这就是我在 mongoose.js 2.0.4 中工作的方式

var query = EmailModel.find({domain:"gmail.com"});
query.sort('priority', 1);
query.exec(function(error, docs){
  //...
});
于 2011-08-30T22:29:40.320 回答
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
})

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

于 2017-08-02T02:04:53.893 回答
8

您可以按以下方式对查询结果进行排序

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

于 2021-03-05T09:00:40.290 回答
6
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 } ]
于 2019-01-04T06:48:56.500 回答
5

使用当前版本的猫鼬(1.6.0),如果您只想按列排序,则必须删除数组并将对象直接传递给 sort() 函数:

Content.find().sort('created', 'descending').execFind( ... );

花了我一些时间,才能做到这一点:(

于 2011-07-13T13:18:04.483 回答
4

这就是我设法排序和填充的方式:

Model.find()
.sort('date', -1)
.populate('authors')
.exec(function(err, docs) {
    // code here
})
于 2012-05-11T14:47:31.647 回答
3
Post.find().sort({updatedAt: 1});
于 2012-11-09T22:25:21.200 回答
3

自 2020 年 10 月起,要解决您的问题,您应该将 .exec() 添加到调用中。不要忘记,如果你想在调用之外使用这些数据,你应该在异步函数中运行类似这样的东西。

let post = await callQuery();

async function callQuery() {
      return Post.find().sort(['updatedAt', 1].exec();
}
于 2020-10-06T20:46:14.880 回答
2

其他人为我工作,但这确实:

  Tag.find().sort('name', 1).run(onComplete);
于 2011-07-30T03:12:03.063 回答
2
Post.find().sort({updatedAt:1}).exec(function (err, posts){
...
});
于 2014-02-11T17:52:26.043 回答
2

从 4.x 开始,排序方法已更改。如果您使用 >4.x。尝试使用以下任何一种。

Post.find({}).sort('-date').exec(function(err, docs) { ... });
Post.find({}).sort({date: -1}).exec(function(err, docs) { ... });
Post.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... });
Post.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... });
Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Post.find({}, null, {sort: '-date'}, function(err, docs) { ... });
Post.find({}, null, {sort: {date: -1}}, function(err, docs) { ... });
于 2020-05-08T20:08:14.907 回答
1
Post.find().sort('updatedAt').exec((err, post) => {...});

参考这里:https ://mongoosejs.com/docs/queries.html

于 2020-07-20T09:51:32.343 回答
1

这就是我所做的,它工作正常。

User.find({name:'Thava'}, null, {sort: { name : 1 }})
于 2019-07-25T06:23:29.620 回答
0

您还可以使用 aggregate() 进行排序

 const sortBy = req.params.sort;
  const limitNum = req.params.limit;
  const posts = await Post.aggregate([
    { $unset: ['field-1', 'field-2', 'field-3', 'field-4'] },
    { $match: { field-1: value} },
    { $sort: { [sortBy]: -1 } },  //-------------------> sort the result
    { $limit: Number(limitNum) },
  ]);
于 2022-01-03T16:29:11.507 回答