HELP Chapter 4 Lab 2 - Logic Operators

Hello I’m getting frustrated, I don’t know what I’m doing wrong here:
db.companies.find({"$and": [{category_code: {"$exists": true, "$ne": null}}, {"$or": [{"founded_year": 2004},{"founded_month": "October"}]}]}).count() //371

With “$and” both checks must be true. So the first one checks if “category_code” exists.
The other one “$or” checks if it matches one of the following, year or month.

What am I doing wrong? I thought I was a good Dev T_T

@edit
I’ve also tried this here:
db.companies.find({"$or": [{category_code: {"$exists": true, "$ne": null}, "founded_year": 2004}, {category_code: {"$exists": true, "$ne": null},founded_month: "October" }]}).count() //652

one more here
db.companies.find({category_code: {"$exists": true, "$ne": null},"$or": [{"founded_year": 2004},{"founded_month": "October"}]}).count() //371

The lab, in my version of the course, asks for category_code to have the value social or web. These 2 values must be present somewhere in you query.

1 Like

HA! i got it, I guess I didn’t get the syntax at first.
I was trying to do
{category_code: { "$or": ['web', 'social'] }}
I even think that this syntax looks nicer than
{"$or": [ {category_code: 'web'}, {category_code: 'social'} ]}

The bottom might be faster for the binary search. It just need to binary match the key:value and that’s all, no need getting or matching the values from the array.

Just a comment, from $or:

When using $or with <expressions> that are equality checks for the value of the same field, use the $in operator instead of the $or operator.

The first “nicer” $or is not correct because the argument is not an expression. Within find/match without using $expr an expression is a normally document. (doesn’t have to, but normally is).

The second is fine, but from the quote, we could re-write:

{"category_code": { "$in": ["web", "social"] }}
4 Likes