MongoDB Logical Operators Explained
MongoDB logical operators are used to combine multiple conditions in queries. These operators help developers filter data properly inside databases.
What Are Logical Operators?
Logical operators are used when we want to apply multiple conditions together.
- Find students from Delhi AND BCA course
- Find users from Delhi OR Mumbai
- Find products NOT greater than ₹20000
Main MongoDB Logical Operators
- $and
- $or
- $not
- $nor
Sample Collection Data
db.students.insertMany([
{
name: "Rahul",
course: "BCA",
city: "Delhi",
marks: 85
},
{
name: "Aman",
course: "MCA",
city: "Mumbai",
marks: 72
},
{
name: "Priya",
course: "BCA",
city: "Jaipur",
marks: 45
},
{
name: "Neha",
course: "BCA",
city: "Delhi",
marks: 60
}
])
1. MongoDB $and Operator
The $and operator is used when all conditions must be true.
db.students.find({
$and: [
{ course: "BCA" },
{ marks: { $gt: 80 } }
]
})
This query finds students whose course is BCA and marks are greater than 80.
2. MongoDB $or Operator
The $or operator is used when any one condition can be true.
db.students.find({
$or: [
{ city: "Delhi" },
{ city: "Mumbai" }
]
})
This query finds students from Delhi or Mumbai.
3. MongoDB $not Operator
The $not operator reverses a condition.
db.students.find({
marks: {
$not: { $gt: 80 }
}
})
This query finds students whose marks are not greater than 80.
4. MongoDB $nor Operator
The $nor operator returns documents where all conditions are false.
db.students.find({
$nor: [
{ city: "Delhi" },
{ marks: { $lt: 50 } }
]
})
This query excludes students from Delhi and students with marks less than 50.
More Examples
Example 1
db.students.find({
$and: [
{ city: "Delhi" },
{ course: "BCA" }
]
})
Example 2
db.students.find({
$or: [
{ course: "BCA" },
{ course: "MCA" }
]
})
Example 3
db.students.find({
marks: {
$not: { $lt: 60 }
}
})
Best Practices
- Use indexes for better performance
- Keep queries simple
- Avoid unnecessary nested conditions
- Use projection when needed