Logical Query Operators
Introduction
Hello there and welcome back! In the previous lessons, you were introduced to MongoDB query operators, which enable you to craft more complex queries. Specifically, you covered comparison operators like $gt, $gte, $eq, and others. In this lesson, we'll focus on logical query operators, which allow you to combine multiple conditions to fine-tune your data retrieval. Let's dive in!
Logical Query Operators
In MongoDB, logical query operators are used to filter data based on expressions that evaluate to true or false:
$and: Matches documents where all conditions are true.$or: Matches documents where at least one condition is true.$not: Matches documents where the condition is not true.$nor: Matches documents where none of the conditions are true.
Understanding `$and` Operator
The $and operator combines multiple conditions and only matches documents where all conditions are met. Its syntax requires an array of objects, each representing a condition. Let's run the following command to find the comic books with genres including "Adventure" and featuring Spider-Man as one of the characters:
Looks a little bit bulky, right? Actually, the $and operator is the default in a MongoDB filter object, so you can omit it to simplify the expression, like so:
So why do we need the $and operator at all? Let's imagine we want to use the same field for querying. For example, suppose we want to find comic books that contain both "Sci-Fi" and "Mystic" genres:
This query will give you the wrong result because JSON objects don't allow duplicate fields; it will simply override the earlier value with the latter value. In this specific example, { genres: "Sci-Fi", genres: "Mystic" } will be equivalent to { genres: "Mystic" }. This is where the $and operator comes to the rescue:
This query will correctly find all comic books that belong to both Sci-Fi and Mystic genres. There are no such comics in our collection, by the way.
