Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: order by two fields sum

Tags:

mongodb

SELECT (a+b) as c FROM my_table ORDER BY c ASC;

How can I order by two columns sum in Mongo?

like image 354
fl00r Avatar asked Sep 29 '11 11:09

fl00r


People also ask

How do you sum values in MongoDB?

If used on a field that contains both numeric and non-numeric values, $sum ignores the non-numeric values and returns the sum of the numeric values. If used on a field that does not exist in any document in the collection, $sum returns 0 for that field. If all operands are non-numeric, $sum returns 0 .

How do you arrange data in ascending and descending order in MongoDB?

Ascending/Descending SortSpecify in the sort parameter the field or fields to sort by and a value of 1 or -1 to specify an ascending or descending sort respectively. When comparing values of different BSON types, MongoDB uses the following comparison order, from lowest to highest: MinKey (internal type) Null.

How do I sort numbers in MongoDB?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.


1 Answers

You can't do it easy without an extra action.

To sort on any computed value you need to store it in a document first or in other worlds you need to create extra field 'c', and store a + b in it with each update/insert and only then sort on 'c' as usual.

like image 73
Andrew Orsich Avatar answered Sep 28 '22 18:09

Andrew Orsich