开发者

MongoDB: order by two fields sum

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜