How to sort a collection by date in MongoDB?

I am using MongoDB with Node.JS. I have a collection that contains date and other strings. Date is a JavaScript Date object.

How can I sort this collection by date?

+59
mongodb
Dec 12
source share
9 answers

Just a slight modification to @JohnnyHK's answer

 collection.find().sort({datefield: -1}, function(err, cursor){...}); 

In many cases, we want the latest entries to be returned (e.g. for the latest updates / inserts).

+94
Dec 12 '12 at 21:17
source share

Sorting by date does not require anything special. Just select the desired collection date field.

Updated for the built-in driver 1.4.28 node.js, you can sort ascending on datefield any of the following methods:

 collection.find().sort({datefield: 1}).toArray(function(err, docs) {...}); collection.find().sort('datefield', 1).toArray(function(err, docs) {...}); collection.find().sort([['datefield', 1]]).toArray(function(err, docs) {...}); collection.find({}, {sort: {datefield: 1}}).toArray(function(err, docs) {...}); collection.find({}, {sort: [['datefield', 1]]}).toArray(function(err, docs) {...}); 

'asc' or 'ascending' can also be used instead of 1 .

To sort in descending order, use 'desc' , 'descending' or -1 instead of 1 .

+27
Dec 12 '12 at 21:11
source share

Sushant Gupta's answers are a bit outdated and no longer work.

The following snippet should look like this:

collection.find({}, {"sort" : ['datefield', 'asc']} ).toArray(function(err,docs) {});

+14
Jul 08 '14 at 9:27
source share

This worked for me:

 collection.find({}, {"sort" : [['datefield', 'asc']]}, function (err, docs) { ... }); 

Using Node.js, Express.js and Monk

+10
Jan 14 '15 at 8:00
source share
 collection.find().sort('date':1).exec(function(err, doc) {}); 

it worked for me

indicated by https://docs.mongodb.org/getting-started/node/query/

+6
Feb 13 '16 at 8:57
source share

Additional area [] A bracket is required for the sort parameter to work.

 collection.find({}, {"sort" : [['datefield', 'asc']]} ).toArray(function(err,docs) {}); 
+4
Aug 13 '14 at 17:06
source share

From mongoose, it's simple:

 collection.find().sort('-date').exec(function(err, collectionItems) { // here your code }) 
+3
Oct 19 '15 at 20:52
source share
 db.getCollection('').find({}).sort({_id:-1}) 

This sorts your collection in descending order depending on the insertion date.

+3
Jun 29 '17 at 1:59 on
source share

if your date format is as follows: 02/14/1989 ----> you may find some problems

you need to use ISOdate as follows:

 var start_date = new Date(2012, 07, x, x, x); 

-----> Result ------> ISODate ("2012-07-14T08: 14: 00.201Z")

now just use the query as follows:

  collection.find( { query : query ,$orderby :{start_date : -1}} ,function (err, cursor) {...} 

what he:)

+2
Apr 27 '15 at 14:19
source share



All Articles