2016-04-19 82 views
1

我有一個JSON文件MongoDB的排序按鍵的總和

{ 
    { 
     "_id" : ObjectId("5715c4bbac530eb3018b456a"), 
     "content_id" : "5715c4bbac530eb3018b4569", 
     "views" : NumberLong(200), 
     "likes" : NumberLong(100), 
     "comments" : NumberLong(0) 
    }, 
    { 
     "_id" : ObjectId("5715c4bbac530eb3018b4568"), 
     "content_id" : "5715c4bbac530eb3018b4567", 
     "views" : NumberLong(300), 
     "likes" : NumberLong(200), 
     "comments" : NumberLong(0) 
    }, 
    { 
     "_id" : ObjectId("5715c502ac530ee5018b4956"), 
     "content_id" : "5715c502ac530ee5018b4955", 
     "views" : NumberLong(500), 
     "likes" : NumberLong(0), 
     "comments" : NumberLong(200) 
    } 
} 

我們如何能夠通過SUM排序文檔順序(「意見」,「喜歡」,「意見」)

像在mysql

SELECT SUM(key1, key2, key3) AS key 
FROM document 
ORDER BY key 

在此先感謝。

+0

您必須使用聚合方法才能首先計算總和,然後使用它對數據進行排序。 – Spade

回答

2

首先做一個投影,以獲得所有喜歡,觀點和評論的總和,然後根據該總和進行排序。我正在考慮通過的content_id組是否需要在第二個片段

db.test.aggregate([ 
    { $project : { "_id" : "$content_id", "total" : { $add : [ "$likes", "$views", "$comments"]}}}, 
    { $sort : { "total" : 1 }} 
]) 

如果你根據你的測試數據需要一組操作如果CONTENT_ID可以複製

db.test.aggregate([ 
    { $project : { "_id" : "$content_id", "total" : { $add : [ "$likes", "$views", "$comments"]}}}, 
    { $group : { "_id" : "$_id" , totalPerId : { $sum : "$total" }}}, 
    { $sort : { "total" : 1 }} 
]) 

,您將獲得:

{ "_id" : "5715c502ac530ee5018b4955", "totalPerId" : NumberLong(700) } 
{ "_id" : "5715c4bbac530eb3018b4567", "totalPerId" : NumberLong(500) } 
{ "_id" : "5715c4bbac530eb3018b4569", "totalPerId" : NumberLong(300) } 
+0

謝謝,它工作:) – rahulb