Mongodb sort by sum of keys -
i have json document
{ { "_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) } }
how can sort document order sum("views", "likes", "comments")
something in mysql
select sum(key1, key2, key3) key document order key
thanks in advance.
first projection obtain sum of likes, views , comments, sort based on sum. considering group content_id if needed in second snippet
db.test.aggregate([ { $project : { "_id" : "$content_id", "total" : { $add : [ "$likes", "$views", "$comments"]}}}, { $sort : { "total" : 1 }} ])
if need group operation if content_id can duplicated
db.test.aggregate([ { $project : { "_id" : "$content_id", "total" : { $add : [ "$likes", "$views", "$comments"]}}}, { $group : { "_id" : "$_id" , totalperid : { $sum : "$total" }}}, { $sort : { "total" : 1 }} ])
based on test data, get:
{ "_id" : "5715c502ac530ee5018b4955", "totalperid" : numberlong(700) } { "_id" : "5715c4bbac530eb3018b4567", "totalperid" : numberlong(500) } { "_id" : "5715c4bbac530eb3018b4569", "totalperid" : numberlong(300) }
Comments
Post a Comment