Chapter 4 CRUD Nested $or

I thought I managed to get the right query built out to count the number of companies which fulfill the conditions laid out in the quiz. However, I got numbers like 7 which is not right. I was hoping someone could help me figure out why it wasn’t returning the right number.


db.companies.find({"$and": [{"$or": [{“category_code”: “social”, “category_code”: “web”}]}, {"$or": [{“founded_year”: 2004, “founded_month”: 10}]}]}).count();

Here is how I understand my query:
The logical AND operator is being applied to the two logical OR operators within the query. Therefore, if the internal OR queries both find values which fulfill their requirements then the document will be added to the count. However, if one of the queries fails then it shouldn’t. I think there is something I am overlooking. Thanks!

Your $or are not formatted correctly. In both, you only have one object. You need braces to make the single objects

into 2 objects

{“category_code”: “social”} , { “category_code”: “web”}

You have to do the same with

I see what you’re saying. Indeed I did combine them into a single object which did return a smaller subset. But why was mine incorrect? On the surface it appears that it is performing an OR operator on the category code field but instead it didn’t. It seems to have done something else. Could you explain why my OR version was returning a smaller subset? Thanks!

Because it was not OR but AND.

I am pretty sure that

founded_year equals 2004 --AND-- founded_month equals 10

returns a set that is smaller or equals than

founded_year equals 2004 --OR-- founded_month equals 10.

I do not know how to explain that better than with a concrete example.

{ _id : 1 , founded_year : 2004 , founded_month : 11 }
{ _id : 2 , founded_year : 2005 , founded_month : 10 }
{ _id : 3 , founded_year : 2004 , founded_month : 10 }

All documents are selected with the --OR-- version but only _id:3 is selected with the --AND-- version.

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