Ruby on rails Mongoid顶部位置查询

Ruby on rails Mongoid顶部位置查询,ruby-on-rails,mapreduce,mongoid,Ruby On Rails,Mapreduce,Mongoid,我有一个位置模型,我想找出位置最多的前十个国家 class Location include Mongoid::Document field :country, as: :country, type: String field :name, as: :name, type: String end 我想得到这样的结果: 美国 1000个地点 奥地利 500个地点 德国 100个地点 我如何使用mongoid实现这一点? 我需要地图还原吗?我通过聚合解决了这个问题: @popula

我有一个
位置
模型,我想找出位置最多的前十个国家

class Location
  include Mongoid::Document
  field :country, as: :country, type: String
  field :name, as: :name, type: String
end
我想得到这样的结果:

  • 美国 1000个地点

  • 奥地利 500个地点

  • 德国 100个地点

  • 我如何使用mongoid实现这一点?
    我需要地图还原吗?

    我通过聚合解决了这个问题:

      @popular_countries = Location.collection.aggregate([
          {'$match' => {'country' => {'$ne' => nil}}},
          {'$group' => {'_id' => '$country',
                        'counts' => {'$sum' => 1}}}]).sort_by(&:count)