For instance, I have this JSON inject
{
"insert": "2023-12-08T09:49:00"
}
It is String
I have sent this query here
db.example.find({ "insert" : { "$gt" : "2023-12-08T09:48:00.000Z", "$lt" : "2023-12-08T10:23:38" } })
How is possible that it works? I couldn’t find any implicit conversion between String to UTCdate in docs.
I know this field must be a Date for best practices, but that got me curious if there any kind of explanation.
>Solution :
It works because it’s doing a String comparison between two Strings. One of the many advantages of having dates in UTC-ISO format: YYYY-MM-DDTHH:MM:SSZ. Of course, this is not recommended for dates since string comparisons are much much slower than datetime comparisons, since those are effectively numbers (floating point).
So the parts that make a date bigger are to the left and also blends well with string comparison.
Example: Like "aaa" < "bbb", same goes for "2022" < "2023". It’s just character-by-character comparison.
The string "2023-12-08T09:49:00" is less than the string "2023-12-08T10:23:38" – from left to right in each string, they are equal until 0 < 1. It just happens to also look like a meaningful date format to humans.
Where things go wrong is if you tried to compare datetimes with different timezones, then it’s just treated as a string and it wouldn’t work correctly.
The datetime 2023-12-08T09:49:00Z0800 > 2023-12-08T10:23:38Z0100 (note the timezone specified after Z). But as strings, it would say that the first < the second since no meaning or actual value is extracted from the timezone specification
after Z.