How to Use Query Operators in MongoDB: Syntax and Examples
In MongoDB, use
query operators inside the find() method to filter documents based on conditions. Operators like $eq, $gt, and $in help specify exact matches, ranges, or lists of values in queries.Syntax
MongoDB query operators are used inside the find() method to specify conditions on fields. The general syntax is:
{ field: { : value } } Here, field is the document field to filter, <operator> is the query operator like $eq or $gt, and value is the value to compare.
json
{ field: { $operator: value } }Example
This example shows how to find documents where the age field is greater than 25 using the $gt operator.
mongodb
db.users.find({ age: { $gt: 25 } })Output
[
{ "_id": 1, "name": "Alice", "age": 30 },
{ "_id": 3, "name": "Charlie", "age": 28 }
]
Common Pitfalls
Common mistakes include:
- Using operators without the
$prefix (e.g.,gtinstead of$gt). - Placing operators outside the field object, which causes syntax errors.
- Confusing
$eqwith direct equality (you can use either{ field: value }or{ field: { $eq: value } }).
mongodb
/* Wrong way: missing $ */ db.users.find({ age: { gt: 25 } }) /* Right way: with $ */ db.users.find({ age: { $gt: 25 } })
Quick Reference
| Operator | Description | Example |
|---|---|---|
| $eq | Matches values equal to specified value | { age: { $eq: 30 } } |
| $gt | Matches values greater than specified value | { age: { $gt: 25 } } |
| $lt | Matches values less than specified value | { age: { $lt: 40 } } |
| $in | Matches any value in specified array | { status: { $in: ["A", "B"] } } |
| $ne | Matches values not equal to specified value | { age: { $ne: 20 } } |
Key Takeaways
Always prefix query operators with a $ sign inside the field object.
Use query operators inside the find() method to filter documents by conditions.
Common operators include $eq for equality, $gt for greater than, and $in for matching any value in a list.
Direct equality can be written without $eq as { field: value }.
Check operator placement carefully to avoid syntax errors.