2017-02-24 82 views
0

我有一个Location模型,并想获取位置最多的前十位国家。Mongoid顶部位置查询

class Location 
    include Mongoid::Document 
    field :country, as: :country, type: String 
    field :name, as: :name, type: String 
end 

我想有个结果是这样的:

  1. 美国 1000位置

  2. 奥地利 500位置

  3. 德国 100位置

我该如何用mongoid实现这个功能? 我需要地图缩小吗?

回答

0

我解决它通过聚集:

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