Comparison Operators

Comparison operators allow you to define criteria for document field values when querying.

OperatorDescriptionExample
$eqMatches values that are equal to a specified value.{ age: { $eq: 20 } }
$neMatches all values that are not equal to a specified value.{ age: { $ne: 20 } }
$gtMatches values that are greater than a specified value.{ age: { $gt: 20 } }
$gteMatches values that are greater than or equal to a specified value.{ age: { $gte: 20 } }
$ltMatches values that are less than a specified value.{ age: { $lt: 20 } }
$lteMatches values that are less than or equal to a specified value.{ age: { $lte: 20 } }
$inMatches any of the values specified in an array.{ status: { $in: ["A", "D"] } }
$ninMatches none of the values specified in an array.{ status: { $nin: ["A", "D"] } }

Practical Examples

Let's say we have a `products` collection:

// Find products with price greater than 500
db.products.find({ price: { $gt: 500 } })

// Find users who are NOT 25 years old
db.users.find({ age: { $ne: 25 } })

// Find items where quantity is between 10 and 20 (inclusive)
db.products.find({ qty: { $gte: 10, $lte: 20 } })

// Find users from specific cities
db.users.find({ city: { $in: ["New York", "London", "Tokyo"] } })
Remember: Comparison operators can be used on strings, numbers, dates, and even objects.