In MongoDB, logical operators play a key role in building complex queries by allowing you to combine multiple conditions. These operators help in filtering data by applying logic to the query structure, such as combining conditions with AND, OR, and negating conditions.
Below are the primary logical operators used in MongoDB.
1. $and – Logical AND
The $and operator are used to combine multiple conditions, returning documents that meet all the specified criteria.
Example. Find users who are 30 years old and live in New York.
Code
db.users.find({
$and: [
{ age: 30 },
{ city: 'New York' }
]
})
O/P
2. $or – Logical OR
The $or operator returns documents that satisfy at least one of the given conditions.
Example. Find users who are either 25 years old or live in New York.
Code
db.users.find({
$or: [
{ age: 25 },
{ city: 'New York' }
]
})
O/P
3. $not – Logical NOT
The $not operator inverts the effect of a query, returning documents that do not match the given condition.
Example. Find users whose age is not greater than 30.
Code
db.users.find({
age: {
$not: { $gt: 30 }
}
})
O/P
4. $nor – Logical NOR
The $nor operator returns documents that do not match any of the conditions.
Example. Find users who are neither 30 years old nor live in New York.
Code
db.users.find({
$nor: [
{ age: 30 },
{ city: 'New York' }
]
})
O/P
Conclusion
MongoDB's logical operators like $and, $or, $not, and $nor allow for constructing more advanced queries, making data retrieval flexible and powerful. By combining multiple conditions, these operators provide the ability to fine-tune query results based on complex logic.