Lesson 15 of 50 – Logical Operators in MongoDB
30%

Logical Operators in MongoDB

MongoDB logical operators are used to combine multiple conditions in a query. They help us retrieve documents based on AND, OR, NOR, and NOT conditions.

In this lesson, we will learn how to use logical operators with practical examples from a student management database.

1. What Are Logical Operators?

Logical operators allow us to combine or negate conditions when searching documents.

MongoDB provides four main logical operators:

Operator Meaning Purpose
$and Logical AND All conditions must match.
$or Logical OR At least one condition must match.
$nor Logical NOR None of the conditions may match.
$not Logical NOT Negates a field query condition.

2. Prepare Sample Database

Open MongoDB Shell (mongosh) and select a database named school.

use school

Insert sample documents into a separate collection named logical_students.

db.logical_students.insertMany([
    {
        name: "Rahul",
        age: 18,
        marks: 55,
        course: "ADCA",
        city: "Patna",
        active: true
    },
    {
        name: "Amit",
        age: 20,
        marks: 75,
        course: "Python",
        city: "Gaya",
        active: true
    },
    {
        name: "Priya",
        age: 22,
        marks: 90,
        course: "Web Development",
        city: "Patna",
        active: false
    },
    {
        name: "Neha",
        age: 21,
        marks: 65,
        course: "Python",
        city: "Aurangabad",
        active: true
    },
    {
        name: "Ravi",
        age: 24,
        marks: 40,
        course: "ADCA",
        city: "Gaya",
        active: false
    }
])

Note: Run the insertion command only once to avoid duplicate sample documents.

3. AND Operator ($and)

The $and operator returns documents only when all specified conditions are true.

Syntax
db.collection.find({
    $and: [
        { condition1 },
        { condition2 }
    ]
})
Example 1: Students Older Than 20 and Marks Above 60
db.logical_students.find({
    $and: [
        { age: { $gt: 20 } },
        { marks: { $gt: 60 } }
    ]
})

Result: Priya and Neha.

Example 2: Python Students Who Are Active
db.logical_students.find({
    $and: [
        { course: "Python" },
        { active: true }
    ]
})

Result: Amit and Neha.

Example 3: Students from Patna with Marks Above 70
db.logical_students.find({
    $and: [
        { city: "Patna" },
        { marks: { $gt: 70 } }
    ]
})

Result: Priya.

4. Implicit AND Condition

In MongoDB, you do not always need to write $and explicitly.

When different fields are specified in the same filter, MongoDB applies AND logic automatically.

Example
db.logical_students.find({
    course: "Python",
    active: true
})

This is equivalent to:

db.logical_students.find({
    $and: [
        { course: "Python" },
        { active: true }
    ]
})

Both queries return active students enrolled in Python.

5. OR Operator ($or)

The $or operator returns documents when at least one specified condition is true.

Syntax
db.collection.find({
    $or: [
        { condition1 },
        { condition2 }
    ]
})
Example 1: Students from Patna or Gaya
db.logical_students.find({
    $or: [
        { city: "Patna" },
        { city: "Gaya" }
    ]
})

Result: Rahul, Amit, Priya, and Ravi.

Example 2: Students in ADCA or Python
db.logical_students.find({
    $or: [
        { course: "ADCA" },
        { course: "Python" }
    ]
})

Result: Rahul, Amit, Neha, and Ravi.

Example 3: Students Younger Than 20 or Marks Above 80
db.logical_students.find({
    $or: [
        { age: { $lt: 20 } },
        { marks: { $gt: 80 } }
    ]
})

Result: Rahul and Priya.

6. NOR Operator ($nor)

The $nor operator returns documents that do not satisfy any of the specified conditions.

Syntax
db.collection.find({
    $nor: [
        { condition1 },
        { condition2 }
    ]
})
Example 1: Students Neither from Patna nor Gaya
db.logical_students.find({
    $nor: [
        { city: "Patna" },
        { city: "Gaya" }
    ]
})

Result: Neha.

Example 2: Students Neither in ADCA nor Python
db.logical_students.find({
    $nor: [
        { course: "ADCA" },
        { course: "Python" }
    ]
})

Result: Priya.

Example 3: Students Not Younger Than 20 and Not Scoring Above 80
db.logical_students.find({
    $nor: [
        { age: { $lt: 20 } },
        { marks: { $gt: 80 } }
    ]
})

Result: Amit, Neha, and Ravi.

7. NOT Operator ($not)

The $not operator negates a field query condition.

It is normally used with another operator, such as $gt, $lt, or $regex.

Syntax
db.collection.find({
    field: {
        $not: { operator: value }
    }
})
Example 1: Students Not Older Than 20
db.logical_students.find({
    age: {
        $not: { $gt: 20 }
    }
})

Result: Rahul and Amit.

Example 2: Students Whose Marks Are Not Below 60
db.logical_students.find({
    marks: {
        $not: { $lt: 60 }
    }
})

Result: Amit, Priya, and Neha.

Example 3: Names Not Beginning with R
db.logical_students.find({
    name: {
        $not: { $regex: "^R" }
    }
})

Result: Amit, Priya, and Neha.

Remember: The $not operator may also match documents where the specified field is missing.

8. Difference Between $ne and $not

Both operators can exclude values, but they are used differently.

Example Using $ne
db.logical_students.find({
    age: { $ne: 20 }
})

This finds documents where age is not equal to 20.

Example Using $not
db.logical_students.find({
    age: {
        $not: { $gt: 20 }
    }
})

This finds documents where the condition age greater than 20 is not satisfied.

$ne $not
Compares against one value. Negates another query condition.
Used for not-equal comparisons. Used with operators such as $gt and $regex.
Example: age is not 20. Example: age is not greater than 20.

9. Combining AND and OR Operators

We can combine logical operators to create more advanced queries.

Example 1: Active Students from Patna or Gaya
db.logical_students.find({
    $and: [
        { active: true },
        {
            $or: [
                { city: "Patna" },
                { city: "Gaya" }
            ]
        }
    ]
})

Result: Rahul and Amit.

Example 2: Students Above 20 with ADCA or Python Course
db.logical_students.find({
    $and: [
        { age: { $gt: 20 } },
        {
            $or: [
                { course: "ADCA" },
                { course: "Python" }
            ]
        }
    ]
})

Result: Neha and Ravi.

Example 3: Active Students with Marks Above 60 or Age Below 20
db.logical_students.find({
    active: true,
    $or: [
        { marks: { $gt: 60 } },
        { age: { $lt: 20 } }
    ]
})

Result: Rahul, Amit, and Neha.

10. Logical Operators in Real Applications

Example 1: Student Management System

Find active students whose marks are at least 60.

db.logical_students.find({
    active: true,
    marks: { $gte: 60 }
})
Example 2: Employee Management System

Find employees working in IT or HR.

db.employees.find({
    $or: [
        { department: "IT" },
        { department: "HR" }
    ]
})
Example 3: Product Management System

Find available products costing less than 5,000.

db.products.find({
    available: true,
    price: { $lt: 5000 }
})
Example 4: Library Management System

Find books that are available and belong to either Programming or Database categories.

db.books.find({
    available: true,
    $or: [
        { category: "Programming" },
        { category: "Database" }
    ]
})

11. Logical Operators Quick Reference

Operator Meaning Example
$and All conditions true { $and: [{ age: 20 }, { active: true }] }
$or At least one condition true { $or: [{ age: 20 }, { age: 22 }] }
$nor No condition true { $nor: [{ age: 20 }, { age: 22 }] }
$not Negates a field condition { age: { $not: { $gt: 20 } } }

📝 Practical Assignment

Use the school database and the logical_students collection to complete the following tasks.

  1. Find students whose age is greater than 20 and marks are greater than 60.
  2. Find students enrolled in Python who are active.
  3. Find students from Patna or Gaya using $or.
  4. Find students enrolled in ADCA or Python.
  5. Find students who are neither from Patna nor Gaya.
  6. Find students whose course is neither ADCA nor Python using $nor.
  7. Find students whose age is not greater than 20 using $not.
  8. Find students whose marks are not less than 60.
  9. Find active students from Patna or Gaya.
  10. Find students older than 20 who are enrolled in ADCA or Python.

Challenge: Write a query to find students who are active and either have marks above 70 or are younger than 20.

🧠 Quick Quiz

1. Which operator requires all conditions to be true?


2. Which operator matches when at least one condition is true?


3. Which operator matches when none of the listed conditions is true?