We combine logical and comparison operators to find data that meets multiple conditions at once. This helps us get exactly the information we want.
0
0
Combining logical and comparison operators in MongoDB
Introduction
Finding users who are older than 18 and live in a specific city.
Getting products that cost less than $50 or are on sale.
Selecting orders that are either pending or were placed in the last week.
Filtering books that have more than 300 pages and are written by a certain author.
Syntax
MongoDB
{ $and: [ { field1: { $operator: value } }, { field2: { $operator: value } } ] }
{ $or: [ { field1: { $operator: value } }, { field2: { $operator: value } } ] }$and means all conditions must be true.
$or means at least one condition must be true.
Examples
Finds documents where age is greater than 18 and city is New York.
MongoDB
{ $and: [ { age: { $gt: 18 } }, { city: "New York" } ] }Finds documents where price is less than 50 or the item is on sale.
MongoDB
{ $or: [ { price: { $lt: 50 } }, { onSale: true } ] }Finds books with more than 300 pages and written by Jane Doe.
MongoDB
{ $and: [ { pages: { $gt: 300 } }, { author: "Jane Doe" } ] }Sample Program
This query finds all products in the 'electronics' category that cost less than 100.
MongoDB
db.products.find({
$and: [
{ price: { $lt: 100 } },
{ category: "electronics" }
]
})OutputSuccess
Important Notes
You can combine many conditions inside $and or $or arrays.
If you only use $and, you can also write conditions directly without $and, because MongoDB treats multiple conditions as AND by default.
Logical operators help you build flexible and precise queries.
Summary
Logical operators like $and and $or combine multiple conditions.
Comparison operators like $gt (greater than) and $lt (less than) check values.
Use them together to find exactly the data you want.