Lesson 13 of 50 – Query Operators in MongoDB
26%

Query Operators in MongoDB

MongoDB query operators help us search for documents based on specific conditions. They allow us to compare values, check whether fields exist, match values in arrays, and perform more advanced searches.

In this lesson, we will learn commonly used query operators with practical examples using a student management database.

1. What Are Query Operators?

Query operators are special MongoDB operators used inside query filters to specify conditions for retrieving documents.

Example:

db.students.find({
    age: { $gt: 20 }
})

In this example, $gt means greater than. MongoDB returns students whose age is greater than 20.

Query operators are commonly grouped into categories:

  • Comparison operators
  • Logical operators
  • Element operators
  • Array operators
  • Evaluation operators

2. Prepare Sample Data

Select the database:

use school

Insert sample student documents:

db.students.insertMany([
    {
        name: "Rahul",
        age: 20,
        marks: 75,
        course: "ADCA",
        city: "Patna",
        skills: ["HTML", "CSS"],
        active: true
    },
    {
        name: "Amit",
        age: 22,
        marks: 88,
        course: "Python",
        city: "Gaya",
        skills: ["Python", "SQL"],
        active: true
    },
    {
        name: "Priya",
        age: 19,
        marks: 92,
        course: "Web Development",
        city: "Patna",
        skills: ["HTML", "JavaScript"],
        active: false
    },
    {
        name: "Neha",
        age: 21,
        marks: 65,
        course: "Python",
        city: "Aurangabad",
        skills: ["Python", "HTML"],
        active: true
    },
    {
        name: "Ravi",
        age: 23,
        marks: 55,
        course: "ADCA",
        city: "Gaya",
        skills: ["Excel", "Tally"],
        active: false
    }
])

Note: Run this insertion example only once to avoid creating duplicate sample records.

3. Comparison Operators

Comparison operators compare field values with specified values.

Operator Meaning
$eq Equal to
$ne Not equal to
$gt Greater than
$gte Greater than or equal to
$lt Less than
$lte Less than or equal to
$in Matches any value in an array
$nin Does not match values in an array
Example 1: Equal To ($eq)
db.students.find({
    age: { $eq: 20 }
})
Example 2: Not Equal To ($ne)
db.students.find({
    course: { $ne: "ADCA" }
})
Example 3: Greater Than ($gt)
db.students.find({
    marks: { $gt: 80 }
})
Example 4: Greater Than or Equal To ($gte)
db.students.find({
    age: { $gte: 21 }
})
Example 5: Less Than ($lt)
db.students.find({
    marks: { $lt: 70 }
})
Example 6: Less Than or Equal To ($lte)
db.students.find({
    age: { $lte: 20 }
})

4. Using $in and $nin

Use $in to match a field against any value in a specified array.

Example 1: Find Students in Selected Courses
db.students.find({
    course: {
        $in: ["ADCA", "Python"]
    }
})

This query returns students whose course is either ADCA or Python.

Example 2: Exclude Selected Courses
db.students.find({
    course: {
        $nin: ["ADCA", "Python"]
    }
})

This query returns documents whose course is not one of the specified values. For fields that are missing, $nin can also match the document.

5. Logical Operators

Logical operators combine or reverse query conditions.

Operator Meaning
$and All conditions must match.
$or At least one condition must match.
$nor None of the conditions may match.
$not Negates a field query condition.
Example 1: AND Operator
db.students.find({
    $and: [
        { age: { $gt: 20 } },
        { marks: { $gt: 70 } }
    ]
})
Example 2: OR Operator
db.students.find({
    $or: [
        { course: "ADCA" },
        { city: "Patna" }
    ]
})
Example 3: NOR Operator
db.students.find({
    $nor: [
        { city: "Patna" },
        { course: "Python" }
    ]
})
Example 4: NOT Operator
db.students.find({
    marks: {
        $not: { $gt: 80 }
    }
})

This last query matches documents where marks do not satisfy the greater-than-80 condition. Depending on the field and operator, missing fields can also match a negated query.

6. Element Operators

Element operators check whether a field exists and whether its value has a particular BSON type.

Example 1: Check Whether a Field Exists
db.students.find({
    marks: { $exists: true }
})

This finds documents that contain the marks field.

Example 2: Find Documents Without a Field
db.students.find({
    phone: { $exists: false }
})

This finds documents where the phone field is missing.

Example 3: Check a Field's Data Type
db.students.find({
    age: { $type: "number" }
})

The $type operator lets you search for fields of a specified BSON type. The type name must be supported by MongoDB.

7. Array Operators

Array operators allow you to search documents based on the values stored in array fields.

Example 1: Find Students with HTML Skill
db.students.find({
    skills: "HTML"
})

This matches documents where the skills array contains HTML.

Example 2: Match All Specified Array Values ($all)
db.students.find({
    skills: {
        $all: ["HTML", "CSS"]
    }
})

The array must contain both HTML and CSS, though the values may appear in any order.

Example 3: Match an Array with Exact Elements ($size)
db.students.find({
    skills: {
        $size: 2
    }
})

This matches arrays containing exactly two elements.

8. Evaluation Operators

Evaluation operators support searches such as regular expression matching and certain expression-based conditions.

Example 1: Search Names Beginning with R
db.students.find({
    name: { $regex: "^R" }
})

The ^R pattern matches names beginning with the letter R.

Example 2: Case-Insensitive Search
db.students.find({
    name: {
        $regex: "^r",
        $options: "i"
    }
})

The i option makes the regular expression case-insensitive.

Example 3: Find Documents with Marks Above 80
db.students.find({
    $expr: {
        $gt: ["$marks", 80]
    }
})

The $expr operator allows aggregation expressions to be used inside a query filter.

9. Combine Query Operators

You can combine multiple query conditions to build more specific searches.

Example 1: Active Students Aged Above 20
db.students.find({
    age: { $gt: 20 },
    active: true
})
Example 2: Python Students with Marks at Least 70
db.students.find({
    course: "Python",
    marks: { $gte: 70 }
})
Example 3: Students from Patna or Gaya with Marks Above 60
db.students.find({
    city: { $in: ["Patna", "Gaya"] },
    marks: { $gt: 60 }
})
Example 4: Students Who Are Active and Have HTML Skill
db.students.find({
    active: true,
    skills: "HTML"
})

10. Query Operators Quick Reference

Operator Purpose
$gt Greater than
$gte Greater than or equal to
$lt Less than
$lte Less than or equal to
$eq Equal to
$ne Not equal to
$in Matches any listed value
$nin Does not match listed values
$and All conditions must match
$or At least one condition must match
$exists Checks field existence
$type Matches a BSON data type
$all Matches all specified array elements
$size Matches an array by its size
$regex Matches a regular expression pattern

📝 Practical Assignment

Use the school database and the sample students collection to complete these tasks.

  1. Find students whose age is greater than 20.
  2. Find students whose marks are less than 70.
  3. Find students enrolled in ADCA or Python using $in.
  4. Find students whose city is not Patna using $ne.
  5. Find students whose age is between 20 and 22, inclusive.
  6. Find students from Patna or Gaya using $or.
  7. Find documents where the marks field exists.
  8. Find students whose skills include HTML.
  9. Find students whose skills array contains both HTML and CSS.
  10. Find names beginning with N using $regex.

🧠 Quick Quiz

1. Which operator means greater than?


2. Which operator matches at least one condition?


3. Which operator checks whether a field exists?