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 attributes of different objects in MongoDB object array?
To compare attributes of different objects in a MongoDB object array, use $let along with $indexOfArray to locate specific array elements and compare their values using comparison operators.
Syntax
db.collection.find({
"$expr": {
"$let": {
"vars": {
"element1": {"$arrayElemAt": ["$arrayName", {"$indexOfArray": ["$arrayName.field", "value1"]}]},
"element2": {"$arrayElemAt": ["$arrayName", {"$indexOfArray": ["$arrayName.field", "value2"]}]}
},
"in": {"$comparisonOperator": ["$$element1.attribute", "$$element2.attribute"]}
}
}
});
Sample Data
db.demo366.insertOne({
"Name": "Chris",
"details": [
{
"Id": "John1",
"value": "test"
},
{
"Id": "John2",
"value": 18
},
{
"Id": "John3",
"value": 20
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e57ddd92ae06a1609a00ae7")
}
Example: Compare Values of John2 and John3
Query to find documents where John2's value is less than John3's value ?
db.demo366.find({
"$expr": {
"$let": {
"vars": {
"john2": {"$arrayElemAt": ["$details", {"$indexOfArray": ["$details.Id", "John2"]}]},
"john3": {"$arrayElemAt": ["$details", {"$indexOfArray": ["$details.Id", "John3"]}]}
},
"in": {"$lt": ["$$john2.value", "$$john3.value"]}
}
}
});
{
"_id": ObjectId("5e57ddd92ae06a1609a00ae7"),
"Name": "Chris",
"details": [
{ "Id": "John1", "value": "test" },
{ "Id": "John2", "value": 18 },
{ "Id": "John3", "value": 20 }
]
}
How It Works
-
$indexOfArrayfinds the index position of elements with specific Id values -
$arrayElemAtextracts the complete object at that index position -
$letcreates variables to store the extracted objects -
$ltcompares the value attributes (18 < 20 returns true)
Conclusion
Use $let with $indexOfArray and $arrayElemAt to compare attributes between different objects in MongoDB arrays. This approach allows flexible comparisons using any MongoDB comparison operator.
Advertisements
