Mongodb:获取按动态排名排序的文档 [英] Mongodb: Get documents sorted by a dynamic ranking

查看:463
本文介绍了Mongodb:获取按动态排名排序的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些文件:

{ "_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

排名是一个浮点值,其中: -分数是我文档的scopre属性值 -分母只是NOW(当我执行此查询时)与文档的更新字段之差

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

推荐答案

我是Mongodb和聚合框架的新手,但正在考虑答案

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}})

使用 $ project ,您可以重塑文档以插入预先计算的值(在您的情况下为排名字段).之后,使用 $ sort 进行排序通过将1指定为升序或将-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.

这篇关于Mongodb:获取按动态排名排序的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆