Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "$and" operator in mongodb?

I have a query in mongodb where I have to filter all the cities in India with longitude between 75 and 80, I have this working expression for that

{"$match":{"country":"India","lon":{"$gt":75},"lon":{"$lt":80}}},

This expression is working fine, However while going through the documentation of $and, I noticed that

Using an explicit AND with the $and operator is necessary when the same field or operator has to be specified in multiple expressions.

So according to the documentation, it should not work fine,since I have lon field appearing multiple time but it is working as expected. So can anyone explain to me what scenario documentation is referring to where $and will be required?

like image 549
Dude Avatar asked Sep 19 '25 10:09

Dude


1 Answers

Your conclusion that your query is "working fine" isn't right. Only one of those lon fields will actually be used by the query; probably the second one. So the query will execute fine, but the docs won't be correctly filtered.

Proof at the python prompt:

>>> q = {"$match":{"country":"India","lon":{"$gt":75},"lon":{"$lt":80}}}
>>> q
{'$match': {'country': 'India', 'lon': {'$lt': 80}}}

The rule to follow is that you should only use $and when you have multiple conditions to use for the same key, and you can't combine them into a single object.

As chidham notes, your query should be constructed to combine the two lon conditions as:

{"$match": {"country": "India", "lon": {"$gt": 75, "$lt": 80}}}
like image 166
JohnnyHK Avatar answered Sep 21 '25 00:09

JohnnyHK