$and query output

How many zips in the sample_training.zips dataset are neither over-populated nor under-populated?

In this case, we consider population of more than 1,000,000 to be over- populated and less than 5,000 to be under-populated.

{pop:{"$gt":5000},pop:{"$lt":1000000}} — where this is wrong, being $and is default parameter, why/how this query giving all documents lessthan 1000000 and greater than 5000.

Thankyou for your help

Hi @pen_so,

The issue is that you have repeated the pop field at the same level in your query filter, so only the last field value is actually being set.

You can see this more clearly in the MongoDB shell if you try assigning your query to a variable:

query = { pop: { "$gt": 5000 }, pop: { "$lt": 1000000 }}
{ pop: { '$lt': 1000000 } }

You can use an explicit $and operator if a query has repeated field names or operators at the same level:

query = { $and: [{ pop: { "$gt": 5000 }}, { pop: { "$lt": 1000000 }}]}
{
  '$and': [ { pop: { '$gt': 5000 } }, { pop: { '$lt': 1000000 } } ]
}

… but the more straightforward option would be to combine your $gt and $lt conditions:

query = { pop: { "$gt": 5000, "$lt": 1000000 }}
{ pop: { '$gt': 5000, '$lt': 1000000 } }

For more details, please have a look at Request for explanation! -- Chapter 4: Query Operators Lecture - #12 by Stennie

Regards,
Stennie

5 Likes

thankyou for pointing correct discussion form.

1 Like

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