Chapter 4: Advanced CRUD Operations Lab 2: Logic Operators - Query writing trick

Hi! Can anyone please help me with how to write queries like the solution?

This is my query.

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

This is the solution query.

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

Both return the same value.
But the query of the solution is much simpler. I understand the solution’s query when I see that. But when I check the question again, I can’t think of the query that the solution provided. It’s like starting the query from the middle of the problem. :confused:

How can I write queries like the solution? Is there any trick?

Thanks in advance.

It really just takes time to build up the skills to see the most efficient way to write the query. There aren’t any tricks, just trial and error to start and then building on your skills as time goes along.

1 Like

Hi :wave: @motasimfuad,

Welcome to the MongoDB Community forums :sparkles:

I must say we’re proud that you came up with the MQL query for this problem statement. Now you can work on this query to make it more efficient and simple.

I’ll try to simplify this specific question by converting the textual format into a mathematical format:

[{ "founded_year" AND ("social category_code" OR "web category_code")}
                                     OR 
 {"founded_month" AND ("social category_code" OR "web category_code")}]

Now just take out the common part from both the query separated by OR, which is AND ("social category_code" OR "web category_code")

Now the problem statements get simplified and become similar to the given solution:

[ AND ("social category_code" OR "web category_code") 
      ("founded_year"  OR "founded_month")]

And as @Doug_Duncan mentioned there aren’t any tricks, just constant learning and practicing will improve your skill to come up with an efficient query for a given problem statement.

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

Regards,
Kushagra

3 Likes

Thank you for motivating me to keep practicing.

1 Like

WOW! Thank you so much @Kushagra_Kesav for the explanation. It showed me a far better approach to breaking down the problem than I was previously doing. Really appreciate the help!

2 Likes

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