2017-02-24 62 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)