 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB order by two fields sum?
To order by two fields sum, you can use the aggregate framework. Let us first create a collection with documents
> db.orderByTwoFieldsDemo.insertOne({"Value1":10,"Value2":35}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ca285576304881c5ce84baa") } > db.orderByTwoFieldsDemo.insertOne({"Value1":12,"Value2":5}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ca2855f6304881c5ce84bab") } > db.orderByTwoFieldsDemo.insertOne({"Value1":55,"Value2":65}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ca285686304881c5ce84bac") } Following is the query to display all documents from a collection with the help of find() method
> db.orderByTwoFieldsDemo.find().pretty();
This will produce the following output
{    "_id" : ObjectId("5ca285576304881c5ce84baa"),    "Value1" : 10,    "Value2" : 35 } {    "_id" : ObjectId("5ca2855f6304881c5ce84bab"),    "Value1" : 12,    "Value2" : 5 } {    "_id" : ObjectId("5ca285686304881c5ce84bac"),    "Value1" : 55,    "Value2" : 65 } Case 1: Following is the query to order by two fields sum and get the result in ascending order:
> db.orderByTwoFieldsDemo.aggregate( ... [ ... {$project:{Value1:1, Value2:1, orderBySumValue:{$add: ["$Value1", "$Value2"]}}}, ... {$sort:{orderBySumValue:1}}] ... ); This will produce the following output
{ "_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: Following is the query to order by two fields sum and get the result in descending order
> db.orderByTwoFieldsDemo.aggregate( [ {$project:{Value1:1, Value2:1, orderBySumValue:{$add: ["$Value1", "$Value2"]}}}, {$sort:{orderBySumValue:-1}}] ); This will produce the following output
{ "_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 }Advertisements
 