Sunday, 22 March 2015

how to sort by mongoose or mongodb



The answer is easy:


exports.index = function(req, res) {
News.find().sort('-publishedDate').find(function (err, newss) {
if(err) { return handleError(res, err); }
return res.json(200, newss);
});
};


Example from mongoose:

// sort by "field" ascending and "test" descending
query.sort({ field: 'asc', test: -1 });

// equivalent
query.sort('field -test');


You can find the same solution of mongodb here:


http://docs.mongodb.org/manual/reference/method/cursor.sort/


Three extra things I want to explain:



1. Nature sort:

instead of sorting by column you can also sort all data by insert order (and store order):



How to use it:

db.collection.find().sort( { $natural: 1 } )

You can use .sort({$natural:-1}) with mongodb and mongoose.


Note: But $natural order is not reliable!!!!





2. find().sort(xxxx) , does it query all and sort after?

The answer is no, checkout this:

For mongoose:

http://mongoosejs.com/docs/api.html#query_Query-find




For mongodb:

http://docs.mongodb.org/manual/reference/method/db.collection.find/

that only return a cursor.\


3. When the sort operation consumes more than 32 megabytes, MongoDB returns an error. 

http://docs.mongodb.org/manual/reference/method/cursor.sort/#return-natural-order







No comments:

Post a comment