Stuck on Chapter 4 Lab2

I’m stucked in Chapter 4 Lab2. I am only 1 attemp left, and i don’t know why my query is not not:

  • Problem:

How many companies in the sample_training.companies dataset were either founded in 2004 and either have the social category_code or web category_code, or were founded in the month of October and also either have the social category_code or web category_code?

  • My query:

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

It is much easier to find errors when the code is well formatted:

The following is your code when formatted:

{
    $and:
    [
        { founded_year : 2004 } ,
        {
           $or:
            [
                {category_code:“social”},
                {category_code:“web”},
                {founded_month:10}
            ]
        } ,
        {
            $or :
            [
                {category_code:“social”},
                {category_code:“web”}
            ]
        }
    ]
}

Formatted like that it is clear that founded_year : 2004 must be true for all documents and that is not what the problem statement wants. Personally, I like to create variables for different clause to make it even more readable. For example, the same query with your error but with variables:

year = { founded_year : 2004 } ;
month = { founded_month : 10 } ;
social = { category_code : "social" } ;
web = { category_code : "web" } ;
category = { $or : [ social , web ] } ;
category_or_month = { $or : [ social , web , month ] } ;
query = { $and : [ year , social_or_web_or_month , category ] }

It is much easier then to modify the query to get the correct one because most of the variable are already correct. To get the correct answer the following new variables will be needed.

year_and_category = { $and : [ year , category ] } ;
month_and_category = { $and : [ october , category ] } ;

This is a good example of

1 Like

Thank you! You are rigth, I didn’t see the comma and the meaning was different.