How to sort a collection by date in MongoDB?

后端 未结 10 2049
失恋的感觉
失恋的感觉 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: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 :)

提交回复
热议问题