【问题标题】:How can I get the aggregation framework to work with referenced documents?如何让聚合框架与引用的文档一起使用?
【发布时间】:2013-09-14 17:31:44
【问题描述】:

我得到了以下文档结构:

个人资料has_many DailyProviders。 DailyProvider embeds_one朋友。 Friends 有一个整数字段count。

  • 注意 DailyProvider embeds_ONE 因为,我不打算存储朋友数组。只是每天的总计数。朋友更多地用于“可读性”。

如何使用聚合框架返回按提供者和日期分组的所有计数的总和?

class Stat::Profile
  include Mongoid::Document
  has_many :daily_providers, class_name: 'Stat::DailyProvider'
  field :profile_id, type: Integer
end

class Stat::DailyProvider
  include Mongoid::Document

  belongs_to :profile, class_name: 'Stat::Profile'
  embeds_one :friends, class_name: 'Stat::DailyProvider::Friend', cascade_callbacks: true

  field :provider_name, type: String
  field :date, type: Integer, default: Time.zone.now.strftime('%Y%m%d').to_i

  validates :provider_name, uniqueness: true, presence: true, inclusion: { in: %w(facebook, linkedin) }
end

class Stat::DailyProvider::Friend
  include Mongoid::Document

  embedded_in :daily_provider, class_name: 'Stat::DailyProvider'

  field :count, type: Integer, default: 0
end

我试过了:

Stat::Profile.first.collection.aggregate(
  { '$unwind' => '$daily_providers' },
  { '$unwind' => '$daily_providers.friends' },
  {
    '$project' => {
      '_id' => 1,
      'daily_providers' => '$daily_providers'
    }
  },
  {
    '$group' => {
      '_id' => {
        'date' => '$daily_providers.date'
      },
      'count' => { '$sum' => '$daily_providers.friends.count' }
    }
  }
)

但我得到一个空的[]。聚合框架是否仅适用于嵌入在单个集合中的文档?或者它可以与参考文档一起使用吗?

【问题讨论】:

  • 因为 MongoDB 没有连接?
  • 这是否意味着聚合框架不适用于这样的架构结构?
  • MongoDB 不能跟随对查询或聚合函数中其他集合的引用。只有当前/单个集合。

标签: ruby-on-rails mongodb mongoid ruby-on-rails-4 aggregation-framework


【解决方案1】:

MongoDB 不能自动跟随引用。 DBRef 只是数据库驱动程序的约定。它们对 MongoDB 本身没有任何意义。

MongoDB 不执行 JOIN - 句号。聚合框架一次只能处理一个集合。大多数其他工具(如 MapReduce)也是如此。当你需要做 JOIN 时,你需要在应用层做这个:查询第一个集合,检查结果,并根据它们查询第二个。

因此,MongoDB 鼓励在父对象中嵌入文档,而不是引用它们。

【讨论】:

    猜你喜欢
    • 2014-05-12
    • 2012-10-20
    • 2013-01-11
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    相关资源
    最近更新 更多