【问题标题】:Ruby/Mongodb sorting items descending orderRuby/Mongodb 降序排序项目
【发布时间】:2012-04-03 13:01:35
【问题描述】:

我有一个非常简单的 Mongodb 集合,例如

{ "_id" : ObjectId("objid"), "url" : "http://mydomain.com", "datestamp" : ISODate("2012-03-17T02:00:45.119Z"), "totalcount" : 1 }

我正在尝试查询集合以按降序返回项目,如下所示:

@globallinks = Mongo::Connection.new.db("mydb").collection("mycollect")
@toplinks = @globallinks.find({}, :sort => ["totalcount", Mongo::DESCENDING], :limit => 100)

此查询不按 desc 顺序返回项目。通过扫描记录看起来未排序的结果集,我知道一个事实。

有人有什么想法吗?

【问题讨论】:

    标签: ruby sorting mongodb


    【解决方案1】:

    你正在做的事情对我来说很好,它应该可以工作。

    但是,如果您只有有限数量的 totalcount 值,那么您将获得一个看起来随机的结果集。考虑一个集合,其中大多数 totalcount 值为 2:

    > show = ->(o) { puts "totalcount = #{o['totalcount'].to_i}, other = #{o['other'].to_i}" }
    > t.find().each(&show)
    totalcount = 1, other = 1
    totalcount = 1, other = 4
    totalcount = 2, other = 3
    totalcount = 2, other = 2
    totalcount = 2, other = 1
    totalcount = 2, other = 4
    

    现在我们按totalcount(并且仅按totalcount)对其进行排序:

    > t.find({}, :sort => ['totalcount', Mongo::DESCENDING]).each(&show)
    totalcount = 2, other = 3
    totalcount = 2, other = 2
    totalcount = 2, other = 1
    totalcount = 2, other = 4
    totalcount = 1, other = 1
    totalcount = 1, other = 4
    

    现在我们应用一个 :limit,它恰好只给我们留下了 totalcount == 2 值:

    > t.find({}, :sort => ['totalcount', Mongo::DESCENDING], :limit => 4).each(&show)
    totalcount = 2, other = 3
    totalcount = 2, other = 2
    totalcount = 2, other = 1
    totalcount = 2, other = 4
    

    您是否注意到other 的排序看起来是随机的?但是,如果我们添加一个辅助排序键,我们会得到一些看起来已经排序的东西:

    > t.find({}, :sort => [['totalcount', Mongo::DESCENDING], ['other', Mongo::ASCENDING]], :limit => 4).show(&each)
    totalcount = 2, other = 1
    totalcount = 2, other = 2
    totalcount = 2, other = 3
    totalcount = 2, other = 4
    

    totalcount 听起来像是没有那么多值并且至少包含许多重复值的东西。 :limit:sort 之后应用,因此它可以轻松地选择只有一个或两个totalcount 值的结果。如果没有辅助排序键,您可以获得看起来随机的结果,即使它们是(部分)排序的。

    任何时候您使用可能具有重复值的排序键时,您通常都希望包含一个辅助排序键来合理地对主要组中的内容进行排序。

    【讨论】:

    • 感谢老兄的详细回复!果然我的语法是正确的,但我在变量名中有错字 - 愚蠢的错误!
    猜你喜欢
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多