开发者

MongoDB: order by two fields sum

开发者 https://www.devze.com 2023-04-09 01:48 出处:网络
SELECT (a+b) as c FROM my_table ORDER BY c ASC; How can I order by two column开发者_如何学Pythons sum in Mongo?You can\'t do it easy without an extra action.
SELECT (a+b) as c FROM my_table ORDER BY c ASC;

How can I order by two column开发者_如何学Pythons sum in Mongo?


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.


You can achieve like this query:

db.mycol.aggregate(
    [{$match:{tag:"xxx"}},
    {$project:{tag:1, count_a:1, count_b:1, factor:{$add: ["$count_a", "$count_b"]}}}, 
    {$sort:{factor:-1}}]
)
0

精彩评论

暂无评论...
验证码 换一张
取 消