208

I find no doc for the sort modifier. The only insight is in the unit tests: spec.lib.query.js#L12

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

But it doesn't work for me:

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 に答える
24

アップデート

これが人々を混乱させる場合は、より良い記事があります。マングースのマニュアルでドキュメントの検索クエリの仕組みを確認してください。流暢な API を使用する場合は、メソッドにコールバックを提供しないことでクエリ オブジェクトを取得find()できます。それ以外の場合は、以下で概説するようにパラメーターを指定できます。

オリジナル

Modelmodelのドキュメントに従って、オブジェクトが与えられた場合、これは次のように機能します。2.4.1

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

search specオブジェクトを想定していますがnull、空のオブジェクトを渡すこともできます。

2 番目のパラメーターは、文字列の配列としてのフィールド リストであるため、['field','field2']orを指定しnullます。

3 番目のパラメーターはオブジェクトとしてのオプションで、結果セットを並べ替える機能が含まれます。{ sort: { field: direction } }where fieldis 文字列フィールド名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

于 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 に答える
5

現在のバージョンの mongoose (1.6.0) では、 1 つの列だけで並べ替えたい場合は、配列を削除して、オブジェクトを直接 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 に答える
2

他の人は私のために働いたが、これはうまくいった:

  Tag.find().sort('name', 1).run(onComplete);
于 2011-07-30T03:12:03.063 に答える
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 に答える
2
Post.find().sort({updatedAt:1}).exec(function (err, posts){
...
});
于 2014-02-11T17:52:26.043 に答える
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 に答える