Starting from dates not sorted correctly ....
If you save the date as a string , you need to sort it as a string. It is pretty simple:
2013-11-08
As long as each part of the date string is filled with 0 correctly, the strings will be sorted naturally and according to what you expected.
The full date time is usually stored in UTC:
2013-11-23T10:46:01.914Z
But I also suggest that instead of saving the date value as a string, you consider whether it makes sense to use MongoDB's native date ( reference ). If you look at the MongoDb aggregation structure, you will find that there are many functions that can manipulate these dates, while the string is very limited.
Regarding the sorting of strings, it was pointed out that sorting like a computer stores data, not a sorting method like a human. If you think the string is stored as its ASCII / UTF-8 representation, you should see why sorting works the way it is:
Zoe = [90, 111, 101] geo = [103, 101, 111]
If you need to sort them in descending order as you specify, you should see how the representation of the internal byte "geo" larger than the string "Zoe" (with 103 sorting above 90 in this case).
Typically, the recommendation when using MongoDb is to store strings twice if you need to sort a string with a mixed case:
- Original string (
"Title" ) - Like a normalized string. Perhaps, for example, everything as "lowercase letters", possibly with accented characters, are also converted to a common character. So, you get, for example, a new field called
"SortedTitle" , and your code will use it to sort, but will display the actual " Title" for users.
source share