【问题标题】:Mongoid Top Locations QueryMongoid 热门地点查询
【发布时间】:2017-02-24 04:59:13
【问题描述】:

我有一个Location 模型,想要获取其中位置最多的前十个国家/地区。

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 实现这一目标? 我需要减少地图吗?

【问题讨论】:

    标签: ruby-on-rails mapreduce mongoid


    【解决方案1】:

    我通过聚合解决了:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 2013-10-09
      • 2014-10-08
      相关资源
      最近更新 更多