← Back to MongoDB Course | Chapter 6: Query Operators | Lesson 1 of 7

Comparison operators

Comparison operators test values against numbers, strings or dates.

In this page:

  1. Comparison operators
Syntax
javascript
{ field: { $eq: value } }
{ field: { $ne: value } }
{ field: { $gte: value, $lt: value } }
{ field: { $in: [value1, value2] } }

Comparison operators

$eq, $ne, $gt, $gte, $lt, $lte, $in and $nin cover most comparisons. Comparisons follow BSON type ordering, so numbers do not match strings that look like numbers. Dates compare chronologically.

Note: A string "30" does not match the number 30.

Example: Comparison operators

bash
test> db.scores.insertMany([{ _id: 1, s: 50 }, { _id: 2, s: "50" }, { _id: 3, s: 75 }, { _id: 4 }])
{
  acknowledged: true,
  insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.scores.find({ s: 50 })
[ { _id: 1, s: 50 } ]
test> db.scores.find({ s: { $gt: 60 } })
[ { _id: 3, s: 75 } ]
test> db.scores.find({ s: { $ne: 50 } })
[ { _id: 2, s: '50' }, { _id: 3, s: 75 }, { _id: 4 } ]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Comparing numbers stored as strings
  2. Using $ne and forgetting it also matches missing fields
  3. Comparing dates as strings
Chapter Summary
  • $eq $ne $gt $gte $lt $lte
  • $in and $nin for lists
  • Types must match
  • $ne matches missing fields too
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.