0
0
MongodbHow-ToBeginner · 3 min read

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., gt instead of $gt).
  • Placing operators outside the field object, which causes syntax errors.
  • Confusing $eq with 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

OperatorDescriptionExample
$eqMatches values equal to specified value{ age: { $eq: 30 } }
$gtMatches values greater than specified value{ age: { $gt: 25 } }
$ltMatches values less than specified value{ age: { $lt: 40 } }
$inMatches any value in specified array{ status: { $in: ["A", "B"] } }
$neMatches 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.