ChatGPT解决这个技术问题 Extra ChatGPT

如何在猫鼬中排序?

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

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

但这对我不起作用:

Post.find().sort(['updatedAt', 1]);
阅读 this answer 以获得最新答案。

A
Akash Kumar Verma

在 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) { ... });

这几乎是Francisco Presencia链接的答案的直接副本。不幸的是,投票最高的答案已经过时并且不必要地冗长。
这在今天还不太正确。 {sort: [['date', 1]]} 不起作用,但 .sort([['date', -1]]) 会起作用。看到这个答案:stackoverflow.com/a/15081087/404699
@steampowered 谢谢,我会进行编辑,如果我弄错了,非常欢迎您告诉我或编辑。
希望看到一些关于结果的评论,特别是。 1-1 值的含义,而不是没有太多上下文的 4 行代码
2
2 revs

这就是我在猫鼬 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
})

在 mongoose 3 中,您不能再使用 Array 进行字段选择 - 它必须是 StringObject
顺便说一句,如果您想要所有字段,您可以在该部分中拉 null(至少在 3.8 中)
A
Akash Kumar Verma

从 Mongoose 3.8.x 开始:

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

在哪里:

criteria 可以是 ascdescascendingdescending1-1

注意:使用引号或双引号

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


S
Syntle

更新:

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
});

在最新的 Mongoose (2.4.10) 中,它是 .sort("updatedAt", -1)
在更最新的 Mongoose(3.5.6-pre,但我很确定它适用于所有 3.x)中,它是 .sort({updatedAt: -1}).sort('-updatedAt')
那么您应该使用 exec(function (posts) {… 而不是 all
我在 Mongoose 4.6.5 中有一个 all() must be used after where() when called with these arguments...
我在 Node.js 中使用它,例如 javascript Post.find().sort({updatedAt: -1}).all((posts) => {
S
Sultan Aslam

猫鼬 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


正如@Sunny Sultan 指出的那样,预示着所有的Post.find({}, null, {sort: '-field'}, function(err, docs) { ... }); 都用于下降,而Post.find({}, null, {sort: 'field'}, function(err, docs) { ... }); 也用于上升。事实上,当我在 http 查询参数中传递字段和排序顺序时,将它们组合成一个字符串并使用这种方式对我的 bd 查询进行排序是我唯一的选择。
A
AJ.

更新

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

原来的

给定一个 model 对象,根据 docs on 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);
};

高温高压


对于投影:我们需要提供包含用空格分隔的列名的字符串。
S
Salida Software

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

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

佚名

与 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
})

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


R
Ramadhani Shemahonge

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

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


J
Jaskaran Singh
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 } ]

P
Philipp Kyeck

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

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

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


M
Mark Nguyen

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

Model.find()
.sort('date', -1)
.populate('authors')
.exec(function(err, docs) {
    // code here
})

c
chovy
Post.find().sort({updatedAt: 1});

F
Frederick Haug

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

let post = await callQuery();

async function callQuery() {
      return Post.find().sort(['updatedAt', 1].exec();
}

F
FrederickCook

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

  Tag.find().sort('name', 1).run(onComplete);

g
gtsouk
Post.find().sort({updatedAt:1}).exec(function (err, posts){
...
});

S
Sunny Sultan

从 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) { ... });

T
Thavaprakash Swaminathan

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

User.find({name:'Thava'}, null, {sort: { name : 1 }})

H
Huỳnh Tấn Lực
Post.find().sort('updatedAt').exec((err, post) => {...});

此处参考:https://mongoosejs.com/docs/queries.html


您好,欢迎来到社区。虽然您的答案可能会提供解决方案,但一个好的答案需要一些解释。请添加一些参考资料和适当的解释。
M
Marzieh Mousavi

您还可以使用 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) },
  ]);