How to Use $eq Operator in MongoDB Queries
In MongoDB, the
$eq operator is used to match documents where a field's value is exactly equal to a specified value. It is commonly used inside a query object like { field: { $eq: value } } to filter results by equality.Syntax
The $eq operator checks if a field's value is equal to the given value.
- field: The name of the field to compare.
- $eq: The equality operator.
- value: The value to compare against.
It is used inside a query object like this:
json
{ field: { $eq: value } }Example
This example finds all documents in the users collection where the age field is exactly 25.
mongodb
db.users.find({ age: { $eq: 25 } })Output
[
{ "_id": ObjectId("..."), "name": "Alice", "age": 25 },
{ "_id": ObjectId("..."), "name": "Bob", "age": 25 }
]
Common Pitfalls
One common mistake is using $eq unnecessarily when a simple equality check works the same. For example, { age: 25 } is equivalent to { age: { $eq: 25 } }.
Another pitfall is confusing $eq with assignment or using it outside query context.
mongodb
/* Wrong: Using $eq outside query */ db.users.insertOne({ name: "Eve", age: { $eq: 30 } }) /* Right: Use $eq only in queries */ db.users.find({ age: { $eq: 30 } })
Quick Reference
Use $eq to test equality in queries. It is optional when testing simple equality because MongoDB treats { field: value } as { field: { $eq: value } }.
Use $eq when you want to be explicit or combine with other operators.
| Operator | Description | Example |
|---|---|---|
| $eq | Matches values that are equal to a specified value | { age: { $eq: 25 } } |
| Simple equality | Shorthand for $eq | { age: 25 } |
Key Takeaways
Use $eq to explicitly match documents where a field equals a value.
Simple equality queries like { field: value } work the same as { field: { $eq: value } }.
Do not use $eq outside query filters, such as in insert or update documents.
Use $eq when combining with other operators for clarity.
Remember $eq is part of MongoDB's query operators for filtering data.