Logical Query Operators in MongoDB
Introduction
Logical Query Operators in MongoDB allow you to create complex queries by combining multiple conditions. They are used to connect different criteria in a query, enabling you to filter documents with logical expressions. These operators are essential for querying data precisely when simple queries aren't enough.
Logical Query Operators
1. $and
Description: The $and
operator is used to combine multiple conditions in a query, returning documents that meet all the specified conditions.
Use Case: Use $and
when you want to filter documents that must satisfy all the given criteria.
Example: Find all students who scored more than 80 in Math and are enrolled in the Science stream.
db.products.find({
$and: [
{ category: "Electronics" },
{ price: { $gt: 1000 } }
]
});
2. $or
Description: The $or
operator is used to combine multiple conditions in a query, returning documents that meet at least one of the specified conditions.
Use Case: Use $or
when you want to find documents that match any of several conditions.
Example: Find all products that are either on sale or have a rating above 4 stars.
db.users.find({
$or: [
{ city: "Mumbai" },
{ age: { $lt: 30 } }
]
});
3. $not
Description: The $not
operator negates the specified condition, returning documents that do not match the given condition.
Use Case: Use $not
when you want to exclude documents that meet a certain condition.
Example: Find all employees who are not working in the "Sales" department.
db.reviews.find({
rating: { $not: { $gt: 4 } }
});
4. $nor
Description: The $nor
operator combines multiple conditions and returns documents that do not match any of the specified conditions.
Use Case: Use $nor
when you want to exclude documents that meet any of the given conditions.
Example: Find all orders that are neither shipped nor have a total amount less than ₹1000.
db.tasks.find({
$nor: [
{ status: "Completed" },
{ priority: "High" }
]
});
Conclusion
Logical Query Operators like $and
, $or
, $not
, and $nor
provide MongoDB with powerful tools for creating complex queries. By understanding how to use these operators, you can filter documents with precision, ensuring your queries meet your application's specific requirements.