简体   繁体   中英

Mongoid Top Locations Query

I have a Location model and wanna fetch the top ten countries with the most locations in it.

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

I wanna have results like this:

  1. USA 1000 Locations

  2. AUSTRIA 500 Locations

  3. GERMANY 100 Locations

How can I achieve that with mongoid? Do I need a map reduce?

I solved it by aggregation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM