Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 70 ยท Query operators

Comparison Operators

Learn MongoDB comparison operators: $eq, $ne, $gt, $gte, $lt, $lte, $in and $nin, range queries, and how type bracketing limits matches across types.

Equality filters only get you so far. Real questions sound like "products under 20 dollars", "orders placed this month" or "customers in one of these five cities". MongoDB answers them with query operators: special field names that start with a dollar sign and sit inside the condition for a field.

This lesson covers the comparison family: $eq, $ne, $gt, $gte, $lt, $lte, $in and $nin. They are the building blocks for almost every filter you will write. You should know basic filters from Finding Documents. Combining conditions with OR and NOT comes in Logical Operators.

The mongosh listings are real MongoDB commands and are read-only. The runnable examples use the JavaScript practice engine from The Practice Engine Used in This Tutorial, which implements these operators, including the type rules, over an array of documents. It is a stand-in, not a database.

The comparison family

$eq / $ne Equal, not equal.
$gt / $gte Greater than, or equal.
$lt / $lte Less than, or equal.
$in / $nin In a list, not in a list.
1 / 2

The shape of an operator condition

Instead of a plain value, you give the field a document whose keys are operators:

JavaScript
db.products.find({ price: { $gt: 20 } })

Read it as "price is greater than 20". The six value comparisons follow the same pattern:

Operator Meaning
$eq equal to
$ne not equal to
$gt greater than
$gte greater than or equal to
$lt less than
$lte less than or equal to

{ price: { $eq: 20 } } means the same as { price: 20 }. You need $eq mostly when you build queries programmatically and want every condition to look alike.

Range queries

To bound a field on both sides, put several operators in the same condition document:

JavaScript
db.products.find({ price: { $gte: 10, $lt: 50 } })

This is a range: at least 10 and below 50. A frequent beginner mistake is to repeat the field name instead:

JavaScript
{ price: { $gte: 10 }, price: { $lt: 50 } }   // wrong: the second key replaces the first

In a JavaScript object (and in JSON), a repeated key overwrites the earlier one, so only $lt: 50 survives. Keep all operators for one field inside one object. Ranges on dates work the same way and are very common: { createdAt: { $gte: start, $lt: end } } finds everything in a half-open interval, which avoids double counting at the boundaries.

$ne and missing fields

$ne matches every document where the field is not equal to the value, and that includes documents that do not have the field at all. { status: { $ne: "archived" } } therefore returns documents whose status is something else, null, or missing. If you want only documents that have a status different from "archived", add an existence check (see Element and Evaluation Operators).

$in and $nin

$in takes an array of values and matches a document when the field equals any of them. It is a compact replacement for a chain of ORs:

JavaScript
db.customers.find({ city: { $in: ["Oslo", "Bergen", "Trondheim"] } })

$nin is the opposite: the field equals none of the values, and, like $ne, it also matches documents where the field is absent.

JavaScript
db.customers.find({ city: { $nin: ["Oslo", "Bergen"] } })

$in also accepts regular expressions in its list. When the field is an array, $in matches when any element equals any listed value: { tags: { $in: ["vip", "beta"] } } finds documents tagged with either one.

JS Comparison operators in action

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the two "not" lines. $ne and $nin both return the Gift Card, which has no category at all. If that is not what you want, combine them with { category: { $exists: true } }.

Type bracketing

MongoDB can store different types in the same field, and the comparison operators ($gt, $gte, $lt, $lte) only compare values of the same type group, called a bracket. All numeric types (32-bit and 64-bit integers, doubles, decimals) share one bracket, so { qty: { $gt: 5 } } works whether qty was stored as an integer or a double. But strings, dates, booleans and so on are separate brackets:

  • { qty: { $gt: 5 } } does not match a document where qty is the string "10", even though "10" looks bigger. A string is never greater or smaller than a number, it is just in another bracket.
  • { qty: { $lt: "z" } } compares only strings.
  • Dates compare with dates. Store real Date values and compare with Date values. Comparing a date field with an ISO string finds nothing, because the types differ.

Strings compare character by character using their binary order unless you configure a collation, so "10" is smaller than "9" (because "1" comes before "9") and uppercase letters sort before lowercase letters. If you ever store numbers as strings, range queries will give surprising answers. The fix is to store numbers as numbers.

This strictness is a feature: it avoids accidental conversions. It is also why a messy collection with mixed types for one field gives incomplete results with no error. Keep each field to one type, and enforce it with Schema Validation.

For an array field, a comparison matches when any element satisfies it. { scores: { $gt: 90 } } matches scores: [70, 95]. Two bounds on the same array field may be satisfied by different elements: { scores: { $gt: 80, $lt: 90 } } matches [70, 95] because 95 is above 80 and 70 is below 90. Use $elemMatch when one element must meet both bounds, as described in Querying Nested Fields and Arrays.

JS Type bracketing, strings and arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first line shows the bracket rule: only the number 10 and the array holding 70 and 95 match qty > 5; the strings "10" and "9", the date and the null do not. The string comparisons treat "10" as smaller than "5" and "9". The date filter matches the date, and the ISO string does not, because it can only match other strings.

Checklist for comparison queries

  • Store each field with a single type, and compare it with the same type.
  • Put several operators for one field in one condition document.
  • Remember that $ne and $nin include documents where the field is missing.
  • For half-open date ranges use $gte and $lt.
  • On array fields, comparisons are satisfied by any element, so bound queries may need $elemMatch.
  • Queries with $ne and $nin are usually not selective, so indexes help them less than equality and range filters. See Common Performance Pitfalls.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which filter finds products with a price of at least 10 and below 50?

    Both bounds go inside one condition document. Repeating the field name overwrites the first condition, so the third option only applies the upper bound.
  2. 2. A document has qty: '10' (a string). Does { qty: { $gt: 5 } } match it?

    Comparison operators only compare values in the same type bracket. The query silently skips documents of other types.
  3. 3. Which documents does { status: { $ne: 'done' } } return?

    $ne also matches documents where the field is missing. Add $exists: true if you want to require the field.
  4. 4. How does { city: { $in: ['Oslo', 'Bergen'] } } behave?

    $in matches when the field equals any value in the list. $nin is the negation.

Summary

  • Operators are dollar-prefixed keys inside a field's condition: { field: { $gt: value } }.
  • $eq, $ne, $gt, $gte, $lt, $lte compare values; put several operators for one field in one object to build a range.
  • $in matches any of a list of values (and any element of an array field); $nin matches none of them.
  • $ne and $nin also match documents that lack the field.
  • Comparison operators only compare values of the same type bracket: numbers with numbers, strings with strings, dates with dates.
  • Strings compare character by character, so numbers stored as strings sort and range-query incorrectly.

Next, combine conditions with Logical Operators.