你正在做的事情对我来说很好,它应该可以工作。
但是,如果您只有有限数量的 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 值的结果。如果没有辅助排序键,您可以获得看起来随机的结果,即使它们是(部分)排序的。
任何时候您使用可能具有重复值的排序键时,您通常都希望包含一个辅助排序键来合理地对主要组中的内容进行排序。