What is the $eq operator in MongoDB?
Overview
$eq is a query operator in MongoDB. Like other query operators, it specifies a condition. It checks for equality by matching a set of documents whose paths or fields are equal to the specified value.
Syntax
{<field>: {$eq: <value> }}
Parameters
field: This is a valid document path.
value: This is the value that needs to be matched.
Return value
This query operator returns the set of documents whose paths are equal to the specified value.
Example
In the example given below, we will use the $eq operator to query a pre-existing collection to match fruits whose quantity is equal to 20.
Given that a fruits collection has the following documents:
{
"_id" : ObjectId("60f0553e1cd9041c4014a2a3"),
"name": "apple",
"quantity": 20
}
{
"_id" : ObjectId("60fd8fb788fe0e2118ddbd7c"),
"name": "mango",
"quantity": 20
}
{
"_id" : ObjectId("6120216fbb75d313c4d65af4"),
"name": "watermelon",
"quantity": 10
}
Let’s query the collections using the $eq operator to match fruits whose quantity is equal to 20:
db.fruits.find("quantity", {$eq: 20}).pretty()
This is the result that will be generated after we run the command given above:
{
"_id" : ObjectId("60f0553e1cd9041c4014a2a3"),
"name": "apple",
"quantity": 20
}
{
"_id" : ObjectId("60fd8fb788fe0e2118ddbd7c"),
"name": "mango",
"quantity": 20
}
Code explanation
From the fruits collection, we were able to select documents whose quantity field is equal to 20. We selected them using the $eq operator. Only two documents were returned after the query because only those two documents had a quantity field that was equal to 20.