Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why this query works in MongoDB?

For instance, I have this JSON inject

{
    "insert": "2023-12-08T09:49:00"
}

It is String

I have sent this query here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading