Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to compare two fields in aggregation filter with MongoDB?
To compare two fields in an aggregation filter with MongoDB, use the $filter operator within a $project stage. This allows you to filter array elements based on field comparisons using the $eq operator.
Syntax
db.collection.aggregate([
{
$project: {
arrayField: {
$filter: {
input: "$arrayField",
as: "variable",
cond: { $eq: ["$$variable.field", "$otherField"] }
}
}
}
}
]);
Sample Data
db.demo137.insertOne({
Name1: "Chris",
Name2: "David",
Detail1: [
{_id: "John", Name3: "Chris"},
{_id: "Chris", Name3: "Chris"}
],
Detail2: [
{_id: "David", Name3: "Chris"},
{_id: "Carol", Name3: "Chris"},
{_id: "John", Name3: "Chris"}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e31b4cefdf09dd6d08539a0")
}
Display all documents from the collection ?
db.demo137.find();
{
"_id": ObjectId("5e31b4cefdf09dd6d08539a0"),
"Name1": "Chris",
"Name2": "David",
"Detail1": [
{ "_id": "John", "Name3": "Chris" },
{ "_id": "Chris", "Name3": "Chris" }
],
"Detail2": [
{ "_id": "David", "Name3": "Chris" },
{ "_id": "Carol", "Name3": "Chris" },
{ "_id": "John", "Name3": "Chris" }
]
}
Example: Filter Arrays Based on Field Comparison
Filter Detail1 and Detail2 arrays to show only elements where the _id matches Name1 and Name2 respectively ?
db.demo137.aggregate([
{
$project: {
_id: 0,
Name1: 1,
Name2: 1,
Detail1: {
$filter: {
input: "$Detail1",
as: "out",
cond: {
$eq: ["$$out._id", "$Name1"]
}
}
},
Detail2: {
$filter: {
input: "$Detail2",
as: "out",
cond: {
$eq: ["$$out._id", "$Name2"]
}
}
}
}
}
]);
{
"Name1": "Chris",
"Name2": "David",
"Detail1": [
{ "_id": "Chris", "Name3": "Chris" }
],
"Detail2": [
{ "_id": "David", "Name3": "Chris" }
]
}
Key Points
- Use
$$variableto reference the current element in the$filtercondition. - Use
$fieldNameto reference document-level fields for comparison. - The
$eqoperator performs exact field-to-field comparison within the filter condition.
Conclusion
The $filter operator with $eq effectively compares fields within aggregation pipelines. This approach filters array elements by matching their properties against other document fields, providing precise control over query results.
Advertisements
