Skip to content

Querying & Filtering

Comparison Operators

$eq, $ne, $gt, $gte, $lt, $lte, $in and $nin through practical filters, not a syntax list.

BeginnerAbout 6 minutes

Operators hang on the field. { age: { $gt: 25 } } reads: the age field must be greater than 25. You already used $eq without writing it.

db.users.find({ age: { $gt: 25 } })

db.products.find({ price: { $gte: 1000, $lte: 5000 } })
Range on a number
{ name: "Rahul", age: 28, ... }
{ name: "Mechanical Keyboard", price: 4500, ... }
Rahul is 28. A keyboard at 4500 sits in that price band.
db.orders.find({ status: { $ne: "cancelled" } })
Not equal. Cancelled orders stay out of a revenue query.
db.orders.find({
  status: { $in: ["completed", "shipped"] }
})

db.users.find({
  city: { $nin: ["Mumbai", "Delhi"] }
})
One field, several values — $in. The opposite is $nin.

$in is the usual way to say 'this or this or this' on one field. $or is for conditions on different fields — next lesson. $eq / $ne / $gt / $gte / $lt / $lte / $in / $nin is the set you should be able to write cold.

OperatorKeeps the document when
$eqField equals the value (the default)
$neField is not equal — also matches missing fields
$gt / $gteGreater than / greater than or equal
$lt / $lteLess than / less than or equal
$in / $ninValue is / is not in the list

Interview question

How do you query a range on one field, and when do you use $in?

Think about it first.

Practice

Ranges and a combined amount + status filter.