Introduction
We combine comparison operators to find data that meets multiple conditions at the same time.
Jump into concepts and practice - no test required
We combine comparison operators to find data that meets multiple conditions at the same time.
{ field: { $operator1: value1, $operator2: value2 } }{ age: { $gt: 18, $lt: 30 } }{ price: { $gte: 10, $lte: 50 } }{ score: { $ne: 100, $lt: 90 } }This query finds all products with a price greater than 20 and less than 100.
db.products.find({ price: { $gt: 20, $lt: 100 } })Combining operators inside one field means all conditions must be true for that field.
You cannot combine conflicting operators like $gt: 10 and $lt: 5 because no value can satisfy both.
Combine comparison operators inside a field to filter data with multiple conditions.
Use $gt, $lt, $gte, $lte, $ne to compare values.
All combined conditions must be true for a document to match.
age is greater than 20 and less than 30?{ age: { $gt: 20, $lt: 30 } } combines both conditions on the same field correctly.score is not equal to 50 and less than or equal to 100?score, so they go together inside one object.$ne: 50 and $lte: 100 inside score. { score: { $ne: 50 }, $lte: 100 } separates $lte outside, which is invalid syntax.products with documents like { price: 150, stock: 30 }, what will the query { price: { $gt: 100, $lt: 200 }, stock: { $gte: 20, $lte: 40 } } return?{ quantity: { $gt: 10 }, $lt: 50 }quantity field object, which is invalid syntax in MongoDB queries.quantity object like { quantity: { $gt: 10, $lt: 50 } }.rating is greater than 3 but not equal to 5, and reviews are between 10 and 100 inclusive. Which query correctly combines these conditions?$gt: 3 and $ne: 5 must be inside the same rating object to apply both conditions.$gte: 10 and $lte: 100 inside the reviews object.rating field, which is invalid. { rating: { $gt: 3, $ne: 5, $gte: 10 }, reviews: { $lte: 100 } } incorrectly adds $gte: 10 to rating. { rating: { $gt: 3, $ne: 5 }, reviews: { $gt: 10, $lt: 100 } } uses exclusive operators for reviews, which is incorrect.