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?
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.
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.
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.
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} } ] )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With