Chapter 4: Advanced CRUD Operations | Lab 2: Logic Operators

I have since found the right query, but want to know why this query doesn’t give the right answer. Its syntactically correct (runs with no errors), but returns the number 8, which is wrong.

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

Can you edit the code so it looks “pretty”? anyways, to give an idea, the numbers, levels, and order of $and and $or are important, and I see too many of them.

please check your logic, try to use an IDE that understands JSON, and use a prettier to format your query so that you can see it better.

Alternatively to using an IDE, I like to used JS variables to reduce chance of errors by simplifying the structure.

year = { funded_year : 2004 }
month = {funded_month:10}
web ={category_code:"web"}
social={category_code:"social"}
code={"$or":[web,social]}
year_and_code={"$and":[year,code]}
month_and_code={"$and":[month,code]}
...
3 Likes

Hi @Jake_Saunders, welcome to the community.
Though your aggregation pipeline is syntactically correct, you root $or operator is getting just one expression, you need to close the whole first expression containing $and before mentioning the second $and operator, otherwise it will not perform an or operation between both the query expressions.
TLDR; your current query is similar to the following structure:

{
  $or: [
    {
      $and: [
        { ...firstExpression... },
        {
          $and: { ...secondExpression... }
        }
      ]
    }
  ]
}

But it should follow the following structure to perform or between both the $and expressions:

{
  $or: [
    {
      $and: { ...firstExpression... }
    },
    {
      $and: { ...secondExpression... }
    }
  ]
}

I hope that helps.

If you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
MongoDB

3 Likes