Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB sorting date string (mm/dd/yyyy)

Tags:

mongodb

I'm storing date as string in "mm/dd/yyyy" format. I want to sort by this date field. I tried below query with few test data.

db.collection.find().sort({date: -1}).pretty()

and it is working fine. Would this work fine ever or should i convert this to MongoDate for reliable sorting?

like image 425
user10 Avatar asked Aug 18 '16 14:08

user10


People also ask

How do I sort a date string in MongoDB?

We can sort the data using the aggregation method, aggregation method is very useful to sort the date field in ascending or descending order. We can also use order by operator to sort the date type field documents in MongoDB. While using any operator we need to specify the value of ascending or descending order.

Does MongoDB support sorting?

MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted. The sort keys must be listed in the same order as defined in the index.

How do I change the date format in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.


2 Answers

Within MongoDB 3.6 you can now use $dateFromString (https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromString/)

db.logmessages.aggregate( [ {
   $project: {
      date: {
         $dateFromString: {
            dateString: '$date'
         }
      }
   }
}, { $sort: { date : 1} } ] )
like image 73
Kevin Smith Avatar answered Sep 19 '22 09:09

Kevin Smith


With yyyy being last, that sort isn't going to work across years.

Probably best to switch to a yyyy-mm-dd formatted string or an actual Date type. Both of those will sort correctly.

like image 34
JohnnyHK Avatar answered Sep 18 '22 09:09

JohnnyHK