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
MongoDB order by two fields sum?
To order documents by the sum of two fields in MongoDB, use the aggregation framework with $project to calculate the sum and $sort to order the results.
Syntax
db.collection.aggregate([
{ $project: { field1: 1, field2: 1, sumField: { $add: ["$field1", "$field2"] } } },
{ $sort: { sumField: 1 } } // 1 for ascending, -1 for descending
]);
Sample Data
db.orderByTwoFieldsDemo.insertMany([
{ "Value1": 10, "Value2": 35 },
{ "Value1": 12, "Value2": 5 },
{ "Value1": 55, "Value2": 65 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("..."),
ObjectId("...")
]
}
db.orderByTwoFieldsDemo.find();
{
"_id": ObjectId("5ca285576304881c5ce84baa"),
"Value1": 10,
"Value2": 35
}
{
"_id": ObjectId("5ca2855f6304881c5ce84bab"),
"Value1": 12,
"Value2": 5
}
{
"_id": ObjectId("5ca285686304881c5ce84bac"),
"Value1": 55,
"Value2": 65
}
Case 1: Ascending Order by Sum
Order documents by the sum of Value1 and Value2 in ascending order ?
db.orderByTwoFieldsDemo.aggregate([
{ $project: { Value1: 1, Value2: 1, orderBySumValue: { $add: ["$Value1", "$Value2"] } } },
{ $sort: { orderBySumValue: 1 } }
]);
{ "_id": ObjectId("5ca2855f6304881c5ce84bab"), "Value1": 12, "Value2": 5, "orderBySumValue": 17 }
{ "_id": ObjectId("5ca285576304881c5ce84baa"), "Value1": 10, "Value2": 35, "orderBySumValue": 45 }
{ "_id": ObjectId("5ca285686304881c5ce84bac"), "Value1": 55, "Value2": 65, "orderBySumValue": 120 }
Case 2: Descending Order by Sum
Order documents by the sum of Value1 and Value2 in descending order ?
db.orderByTwoFieldsDemo.aggregate([
{ $project: { Value1: 1, Value2: 1, orderBySumValue: { $add: ["$Value1", "$Value2"] } } },
{ $sort: { orderBySumValue: -1 } }
]);
{ "_id": ObjectId("5ca285686304881c5ce84bac"), "Value1": 55, "Value2": 65, "orderBySumValue": 120 }
{ "_id": ObjectId("5ca285576304881c5ce84baa"), "Value1": 10, "Value2": 35, "orderBySumValue": 45 }
{ "_id": ObjectId("5ca2855f6304881c5ce84bab"), "Value1": 12, "Value2": 5, "orderBySumValue": 17 }
Key Points
-
$projectstage calculates the sum using$addoperator and creates a new field -
$sortstage orders documents by the calculated sum field - Use
1for ascending order and-1for descending order
Conclusion
MongoDB aggregation framework with $project and $sort stages effectively orders documents by the sum of two fields. The $add operator calculates the sum, and $sort arranges the results in the desired order.
Advertisements
