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 sort by the difference in array contents in MongoDB?
To sort by the difference in array contents, use MongoDB's aggregation pipeline with $project to calculate differences and $sort to order results. This is useful when comparing values between array elements.
Syntax
db.collection.aggregate([
{ $project: {
"fieldName": "$fieldName",
"difference": {
$subtract: [
{ $arrayElemAt: ["$arrayField", index1] },
{ $arrayElemAt: ["$arrayField", index2] }
]
}
}},
{ $sort: { "difference": 1 } }
]);
Sample Data
db.demo155.insertMany([
{"Scores": [{"Value": 45}, {"Value": 50}]},
{"Scores": [{"Value": 60}, {"Value": 10}]},
{"Scores": [{"Value": 100}, {"Value": 95}]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e354584fdf09dd6d08539e3"),
ObjectId("5e35458efdf09dd6d08539e4"),
ObjectId("5e354599fdf09dd6d08539e5")
]
}
Example: Sort by Difference Between Last Two Elements
Calculate the difference between the last two array elements and sort in descending order ?
db.demo155.aggregate([
{ "$match": { "Scores.1": { "$exists": true } } },
{ "$project": {
"Scores": "$Scores",
"sub": {
"$let": {
"vars": {
"f": { "$arrayElemAt": [ "$Scores", -2 ] },
"l": { "$arrayElemAt": [ "$Scores", -1 ] }
},
"in": { "$subtract": [ "$$l.Value", "$$f.Value" ] }
}
}
}},
{ "$sort": { "sub": -1 } }
]);
{ "_id": ObjectId("5e354584fdf09dd6d08539e3"), "Scores": [ { "Value": 45 }, { "Value": 50 } ], "sub": 5 }
{ "_id": ObjectId("5e354599fdf09dd6d08539e5"), "Scores": [ { "Value": 100 }, { "Value": 95 } ], "sub": -5 }
{ "_id": ObjectId("5e35458efdf09dd6d08539e4"), "Scores": [ { "Value": 60 }, { "Value": 10 } ], "sub": -50 }
How It Works
-
$matchensures documents have at least 2 array elements -
$arrayElemAtwith -2 and -1 gets the second-to-last and last elements -
$letcreates variables to store array elements for cleaner subtraction -
$subtractcalculates the difference: last_value - second_last_value
Conclusion
Use aggregation with $arrayElemAt and $subtract to calculate differences between array elements. The $sort stage then orders documents by these computed differences.
Advertisements
