Introduction to MongoDB $eq Operator

The Mongodb $eq operator is used to match documents that are equal to a specified value.

Syntax

The $eq operator is used in the following way:

{
  field: {
    $eq: value
  }
}

Here, field represents the field to be matched, and value represents the value to be matched.

Use Cases

The $eq operator can be used in various matching scenarios, such as:

Matching documents where a field is equal to a specified value. Used in conjunction with other operators like $and, $or to match multiple conditions.

Examples

Example 1: Matching users with a specific age

Suppose we have a collection called users, which contains information about many users, including their name, age, gender, etc. Now we need to query all user information with the age of 25. We can use the $eq operator to perform the query:

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

The query result is as follows:

{ "_id" : ObjectId("603ed45d307fde96b0a44b6e"), "name" : "Tom", "age" : 25, "gender" : "male" }
{ "_id" : ObjectId("603ed462307fde96b0a44b70"), "name" : "Lucy", "age" : 25, "gender" : "female" }

Example 2: Using with the $and operator

Suppose we have a collection called products, which contains information about many products, including their name, price, stock, etc. Now we need to query information about the product named “iPhone 12” and priced at 6999. We can use the $eq operator and the $and operator to perform the query:

db.products.find({
  $and: [{ name: { $eq: "iPhone 12" } }, { price: { $eq: 6999 } }]
})

The query result is as follows:

{ "_id" : ObjectId("603ed5d5307fde96b0a44b73"), "name" : "iPhone 12", "price" : 6999, "stock" : 100 }

Conclusion

The $eq operator can be used to match documents with specified values and can be combined with other operators to perform multi-condition matching.