CPCODELAB
MongoDB

Query Operators

12 min read

Filtering with Query Operators

MongoDB provides a rich set of query operators prefixed with $. They let you express conditions that go beyond simple equality — ranges, membership tests, logical combinations, and text patterns.

Comparison Operators

js
// Students older than 20
db.students.find({ age: { $gt: 20 } });

// Age between 18 and 22 (inclusive)
db.students.find({ age: { $gte: 18, $lte: 22 } });

// Course is one of these values
db.students.find({ course: { $in: ["Full Stack", "DevOps"] } });

Logical Operators

js
// Enrolled AND age > 20
db.students.find({
  $and: [
    { enrolled: true },
    { age: { $gt: 20 } }
  ]
});

// DevOps OR Data Science students
db.students.find({
  $or: [
    { course: "DevOps" },
    { course: "Data Science" }
  ]
});

Regular Expressions

js
// Names that start with "R" (case-insensitive)
db.students.find({ name: { $regex: "^R", $options: "i" } });

Regex queries without an index do a full collection scan. Always index the fields you query with $regex.

Ready to test yourself?
Practice MongoDB— quiz & coding exercises