← Back to MongoDB Course | Chapter 3: CRUD — Read | Lesson 3 of 7

Query operators ($eq $gt $lt $in)

Operators starting with a dollar sign let filters compare values instead of only matching equality.
Syntax
javascript
db.collection_name.find({ field: { $gt: value } })
db.collection_name.find({ field: { $in: [value1, value2] } })

Query operators ($eq $gt $lt $in)

$eq, $ne, $gt, $gte, $lt and $lte compare values, $in matches any of a list and $nin matches none of them. Several conditions in one filter document are combined with AND. Range queries put two operators on the same field.

Note: Put multiple operators for one field inside one object: { age: { $gte: 20, $lt: 40 } }.

Example: Query operators ($eq $gt $lt $in)

bash
test> db.products.insertMany([
...   { _id: 1, name: "Pen", price: 3 }, { _id: 2, name: "Book", price: 12 },
...   { _id: 3, name: "Lamp", price: 45 }, { _id: 4, name: "Desk", price: 150 }
... ])
{
  acknowledged: true,
  insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.products.find({ price: { $gt: 10 } }, { _id: 0 })
[
  { name: 'Book', price: 12 },
  { name: 'Lamp', price: 45 },
  { name: 'Desk', price: 150 }
]
test> db.products.find({ price: { $gte: 10, $lt: 100 } }, { name: 1, _id: 0 })
[ { name: 'Book' }, { name: 'Lamp' } ]
test> db.products.find({ name: { $in: ["Pen", "Desk"] } }, { name: 1, price: 1, _id: 0 })
[ { name: 'Pen', price: 3 }, { name: 'Desk', price: 150 } ]

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

Related Topics
Common Mistakes
  1. Writing { age: > 30 } which is invalid
  2. Repeating a field key twice in a filter
  3. Forgetting $in needs an array
Chapter Summary
  • $eq $ne $gt $gte $lt $lte compare
  • $in and $nin test lists
  • Multiple conditions are ANDed
  • Ranges combine operators on one field
🔒

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.