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:
USA 1000 Locations
AUSTRIA 500 Locations
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.