MongoDB Tutorial
- Home
- Introduction
- Installation
- Connection & Databases
- CRUD Operations
- Comparison Operators
- Logical Operators
- Array Operators
- Evaluation Operators
- Update Operators
- Projection & Sorting
- Cursor Methods
- Querying Nested Docs
- Upserts & Indexes
- Aggregation Framework
- Data Modeling
- Validations & Transactions
- Geospatial Queries
- Advanced Indexing
- MongoDB with Next.js
- Best Practices
Comparison Operators
Comparison operators allow you to define criteria for document field values when querying.
| Operator | Description | Example |
|---|---|---|
$eq | Matches values that are equal to a specified value. | { age: { $eq: 20 } } |
$ne | Matches all values that are not equal to a specified value. | { age: { $ne: 20 } } |
$gt | Matches values that are greater than a specified value. | { age: { $gt: 20 } } |
$gte | Matches values that are greater than or equal to a specified value. | { age: { $gte: 20 } } |
$lt | Matches values that are less than a specified value. | { age: { $lt: 20 } } |
$lte | Matches values that are less than or equal to a specified value. | { age: { $lte: 20 } } |
$in | Matches any of the values specified in an array. | { status: { $in: ["A", "D"] } } |
$nin | Matches none of the values specified in an array. | { status: { $nin: ["A", "D"] } } |
Practical Examples
Let's say we have a `products` collection:
// Find products with price greater than 500
db.products.find({ price: { $gt: 500 } })
// Find users who are NOT 25 years old
db.users.find({ age: { $ne: 25 } })
// Find items where quantity is between 10 and 20 (inclusive)
db.products.find({ qty: { $gte: 10, $lte: 20 } })
// Find users from specific cities
db.users.find({ city: { $in: ["New York", "London", "Tokyo"] } })Remember: Comparison operators can be used on strings, numbers, dates, and even objects.