Chapter 4 Lab 2, using $regex

Hello, for the lab assignment, where we need to check for the inspections conducted in “NEW YORK”, I tried 2 techniques,

db.inspections.find({“address.city” : {"$regex" : “NEW YORK”} }).count()
and,
db.inspections.find({“address.city” : {"$eq" : “NEW YORK”} }).count()

which gave me result
18303 and 18279

I even tried to check whether the extra docs. is because of different case, so tried for “NEw YORK” which in both cases gave result 0, implying that both of them are case-sensitive.

Could someone please help me understand what is going on.

Side-note :
I even gave db.inspections.find({“address.city” : {"$regex" : /NEW YORK/i } }).count() a try, which gave 18308 results, which included “new york” written in different cases too.

Hi @snigdh_shourya ,
The queries

{“address.city” : {"$regex" : “NEW YORK”} }

and

{“address.city” : {"$eq" : “NEW YORK”} }

are different.
The first one ($regex) finds documents where the field “address.city” contains the string “NEW YORK” anywhere in its value.
For example:

  • “1NEW YORK”
  • “NEW NEW YORK”
  • "NEW YORK "
  • " NEW YORK"

The second query ($eq) finds only documents where the value of the field “address.city” is exactly “NEW YORK”.
By the way, if collation is used, the equality test might be different.
See Comparison of Strings for more information.

Thanks,
Rafael,

2 Likes

Thank you very much, for putting in this much of time and effort into my problem, I understand clearly now.

Just to add to this - to make them equal, you would need to specify that the line should start and end with “NEW YORK” like this:

{“address.city” : {"$regex" : “^NEW YORK$”} }

I wonder if this alternative would have any performance implications (besides of course being a bad idea to begin with)

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.