🍃 MongoDB Tutorial

MongoDB Comparison Operators: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin

A complete guide to MongoDB's comparison query operators with real examples for $eq, $ne, $gt, $gte, $lt, $lte, $in and $nin.

MongoDB Comparison Operators

Comparison operators let you compare a field's value against a given value. They're the building blocks of almost every MongoDB query.

Operator Description
$eq Matches values equal to the given value
$ne Matches values not equal to the given value
$gt Greater than
$gte Greater than or equal to
$lt Less than
$lte Less than or equal to
$in Matches any value in an array
$nin Matches none of the values in an array

$eq — Equal

db.employees.find({ age: { $eq: 26 } })
// same as: db.employees.find({ age: 26 })

db.employees.find({ 'reportinmgr.mgrid': { $eq: 105 } })

{ field: value } is just shorthand for { field: { $eq: value } }.

$ne — Not Equal

$ne also matches documents where the field doesn't exist at all.

db.employees.find({ age: { $ne: 26 } })
db.employees.find({ lang: { $ne: "Hindi" } })

$gt / $gte — Greater Than (or Equal)

db.employees.find({ salary: { $gt: 80000 } })
db.employees.find({ salary: { $gte: 90000 } })

$lt / $lte — Less Than (or Equal)

db.employees.find({ salary: { $lt: 90000 } })
db.employees.find({ age: { $lte: 25 } })

$in — Value in Array

Matches if the field's value equals any of the listed values (this is not a range check).

db.employees.find({ salary: { $in: [16000, 30000] } })
// matches salary of exactly 16000 OR 30000 — not values in between

db.employees.find({ deptwork: { $in: [1, 2] } })

$nin — Value Not in Array

Matches documents where the field's value is not any of the listed values, or the field doesn't exist.

db.employees.find({ deptwork: { $nin: [1, 2] } })
db.employees.find({ lang: { $nin: ['Hindi'] } })

Common Errors & Troubleshooting

  • $in returning nothing when you expected matches — double check the array's values are the same type as what's stored (e.g. $in: ["1", "2"] won't match a field storing the numbers 1, 2).
  • Treating $in like a range — { salary: { $in: [16000, 30000] } } only matches those two exact values, not anything between them. Use $gte/$lte (or BETWEEN-style range operators) for a true range.
  • Forgetting $ne also excludes documents missing the field — $ne behaves a bit counter-intuitively: it matches both "field has a different value" and "field doesn't exist at all," which can surprise you if you expected it to only match existing-but-different values.

Key Takeaways

  • $eq is the implicit default — { field: value } and { field: { $eq: value } } are identical.
  • $in/$nin check membership in a list, not a numeric range.
  • All of these work on embedded fields too, using dot notation like 'reportinmgr.mgrid'.