Querying Documents

Learn about different query operators ($eq, $gt, $lt, $in, etc.) and how to construct complex queries to retrieve specific documents.


MongoDB Essentials: The $eq Operator

Equality Operator ($eq) Explained

In MongoDB, the $eq operator is used to perform an equality comparison. It allows you to find documents where a specific field is equal to a given value. Think of it as the equivalent of the = sign in many programming languages or SQL.

Using $eq to Find Documents

Here's how you can use the $eq operator in your MongoDB queries:

Syntax

 { field: { $eq: value } } 
  • field: The name of the field you want to compare.
  • $eq: The equality operator.
  • value: The value you want to compare the field against.

Example Scenario

Let's say you have a collection called users with documents like this:

 [
          { "_id": ObjectId("6543210fedcba9876543210f"), "name": "Alice", "age": 30, "city": "New York" },
          { "_id": ObjectId("6543210fedcba98765432110"), "name": "Bob", "age": 25, "city": "London" },
          { "_id": ObjectId("6543210fedcba98765432111"), "name": "Charlie", "age": 30, "city": "Paris" }
        ] 

To find all users who are 30 years old, you would use the following query:

 db.users.find( { age: { $eq: 30 } } ) 

This query will return:

 [
          { "_id": ObjectId("6543210fedcba9876543210f"), "name": "Alice", "age": 30, "city": "New York" },
          { "_id": ObjectId("6543210fedcba98765432111"), "name": "Charlie", "age": 30, "city": "Paris" }
        ] 

Short-hand Notation (Implicit Equality)

For simple equality checks, you can often omit the $eq operator entirely. MongoDB implicitly assumes equality if you provide a simple field-value pair in the query.

So, the query above can also be written as:

 db.users.find( { age: 30 } ) 

This will produce the same result as using $eq. The implicit form is generally preferred for readability when doing a simple equality comparison.

Important Considerations

  • $eq can be used with various data types, including numbers, strings, dates, and booleans.
  • Be mindful of case sensitivity when comparing strings.

Conclusion

The $eq operator (or its implicit form) is a fundamental tool for querying data in MongoDB. It allows you to easily retrieve documents that match a specific criterion based on field values.