Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort in mongoose?

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]); 
like image 461
Philippe Rathé Avatar asked Nov 29 '10 00:11

Philippe Rathé


People also ask

What is sort in mongoose?

sort() takes an object as parameter where the values are 1 or -1. Use -1 for descending order and 1 for ascending.

How do I sort a query in MongoDB?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

What is the use of sort () in MongoDB?

This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts field.


1 Answers

In Mongoose, a sort can be done in any of the following ways:

    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) { ... }); 
like image 54
iwein Avatar answered Sep 21 '22 16:09

iwein