How to sort a collection by date in MongoDB?

后端 未结 10 2016
失恋的感觉
失恋的感觉 2020-12-07 14:27

I am using MongoDB with Node.JS. I have a collection which contains a date and other rows. The date is a JavaScript Date object.

How can I sort this col

相关标签:
10条回答
  • 2020-12-07 14:44

    With mongoose I was not able to use 'toArray', and was getting the error: TypeError: Collection.find(...).sort(...).toArray is not a function. The toArray function exists on the Cursor class from the Native MongoDB NodeJS driver (reference).

    Also sort accepts only one parameter, so you can't pass your function inside it.

    This worked for me (as answered by Emil):

    collection.find().sort('-date').exec(function(error, result) {
      // Your code
    })
    
    0 讨论(0)
  • 2020-12-07 14:48
    db.getCollection('').find({}).sort({_id:-1}) 
    

    This will sort your collection in descending order based on the date of insertion

    0 讨论(0)
  • 2020-12-07 14:51

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

    you need to use ISOdate like this :

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

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

    now just use the query like this :

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

    that's it :)

    0 讨论(0)
  • 2020-12-07 14:52

    Sorting by date doesn't require anything special. Just sort by the desired date field of the collection.

    Updated for the 1.4.28 node.js native driver, you can sort ascending on datefield using any of the following ways:

    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 in place of the 1.

    To sort descending, use 'desc', 'descending', or -1 in place of the 1.

    0 讨论(0)
  • 2020-12-07 14:52

    Additional Square [ ] Bracket is required for sorting parameter to work.

    collection.find({}, {"sort" : [['datefield', 'asc']]} ).toArray(function(err,docs) {});
    
    0 讨论(0)
  • 2020-12-07 14:53

    Sushant Gupta's answers are a tad bit outdated and don't work anymore.

    The following snippet should be like this now :

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

    0 讨论(0)
提交回复
热议问题