Comparison Operators: $eq, $gt, $lt, $in
Learners will use comparison operators to filter documents by numeric ranges, exact matches, and membership in a list.
Beyond Equality Filters
Simple equality filters like { status: 'active' } are useful, but real queries need more nuance. MongoDB provides a rich set of query operators prefixed with $ that express conditions beyond simple equality. These operators let you filter by numeric ranges, membership in a list, value presence, and pattern matching.
Comparison operators are the most commonly used category. They work on any comparable BSON type: numbers, strings (lexicographic comparison), dates, and even ObjectIds (chronological order, since ObjectIds encode timestamps).
$eq: Explicit Equality
The $eq operator explicitly tests for equality: { age: { $eq: 30 } }. In most cases, the shorthand { age: 30 } is identical and preferred for readability—$eq is mainly useful when the operator is needed inside another expression like $expr.
One difference: $eq inside aggregation pipeline expressions is required when comparing two field values (e.g., { $eq: ['$price', '$salePrice'] }). In regular find filters, stick to the shorthand equality syntax unless a specific context requires the operator form.
// These two queries are equivalent in find()
db.users.find({ age: 30 });
db.users.find({ age: { $eq: 30 } });
// $eq is useful inside $expr for field-to-field comparison:
db.products.find({
$expr: { $eq: ['$price', '$salePrice'] }
});
// Returns products where price equals salePriceAll lessons in this course
- Comparison Operators: $eq, $gt, $lt, $in
- Logical Operators: $and, $or, $nor, $not
- Element Operators and Type Checks
- Regex Queries and Pattern Matching