MongoDB $eq
Operator
The $eq
operator in MongoDB is used to compare whether a specified expression is equal to another expression. It is commonly employed within the $match
stage of an aggregation pipeline to filter documents based on equality. This guide will cover the syntax, examples, output, explanations, use cases, important points, and a summary of using the $eq
operator in MongoDB aggregation.
Syntax
{ $match: { field: { $eq: value } } }
$match
: Aggregation stage to filter documents.field
: The field on which to apply the$eq
operator.$eq
: The operator that checks if the field value is equal to the specified value.value
: The value to compare against.
Example
Consider a collection named employees
with documents containing department
and position
fields. We want to find employees whose department is equal to "IT".
db.employees.aggregate([
{
$match: {
department: { $eq: "IT" }
}
}
]);
Output
The output will display documents from the employees
collection where the department
is equal to "IT".
[
{ "_id": ObjectId("..."), "name": "Alice", "position": "Developer", "department": "IT" },
{ "_id": ObjectId("..."), "name": "Bob", "position": "DBA", "department": "IT" },
// ... other documents
]
Explanation
- The
$match
stage is used to filter documents based on the condition that thedepartment
field is equal to "IT".
Use
The $eq
operator in MongoDB is used for:
- Filtering documents based on equality in the
$match
stage. - Narrowing down the result set to include only documents where a specific field is equal to a specified value.
Important Points
- The
$eq
operator is part of the rich set of comparison operators available in MongoDB. - It can be combined with other operators to create complex filtering conditions.
Summary
The $eq
operator in MongoDB is a fundamental tool for filtering documents based on equality. It is commonly used in aggregation pipelines to narrow down the result set and retrieve documents where specific field values are equal to specified values. Understanding how to use the $eq
operator is crucial for MongoDB developers working with aggregation pipelines to filter and analyze data.