Mongodb: Get documents sorted by a dynamic ranking

时光总嘲笑我的痴心妄想 提交于 2020-01-03 04:36:29

问题


I have these documents:

{ "_id" : ObjectId("52abac78f8b13c1e6d05aeed"), "score" : 125494, "updated" : ISODate("2013-12-14T00:55:20.339Z"), "url" : "http://pictwittrer.com/1crfS1t" }
{ "_id" : ObjectId("52abac86f8b13c1e6d05af0f"), "score" : 123166, "updated" : ISODate("2013-12-14T00:55:34.354Z"), "url" : "http://bit.ly/JghJ1N" }

Now, i would like to get all documents sorted by this dynamic ranking:

ranking = score / (NOW - updated).abs

ranking is a float value where: - score is the value of scopre property of my document - the denominator is just the difference between NOW (when I'm executing this query) and updated field of my document

I'd want to do this because I want the old documents are sorted last


回答1:


I'm new to Mongodb and aggregation frameworks but considering the answer Tim B gave I came up with this:

db.coll.aggregate(
      { $project : {
                     "ranking" : { 
                                  "$divide" : ["$score", {"$subtract":[new Date(), "$updated"]}]
                                 }
                   }
      },
      { $sort : {"ranking" : 1}})

Using $project you can reshape documents to insert precomputed values, in your case the ranking field. After that using $sort you can sort the documents by rank in the order you like by specifying 1 for ascending or -1 for descending.

I'm sorry for the terrible code formatting, I tried to make it as readable as possible.




回答2:


Look at the MongoDB aggregation framework, you can do a project to create the score you want and then a sort to sort by that created score.

http://docs.mongodb.org/manual/core/aggregation-pipeline/

http://docs.mongodb.org/manual/reference/command/aggregate/#dbcmd.aggregate



来源:https://stackoverflow.com/questions/20578496/mongodb-get-documents-sorted-by-a-dynamic-ranking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!