如何与" secondary"进行聚合Mongoid中的读取模式?

时间:2018-04-19 17:28:04

标签: ruby mongodb aggregation-framework mongoid

如何使用secondary模式读取此聚合?这是一个例子:

class User
  include Mongoid::Document

  field :name, type: String
  field :status, type: String
  field :balance, type: Float
end


User.collection.aggregate(
  {
    '$group' => {
      'status' => '$status',
      'total' => { '$sum' => '$balance' }
    }
  }
)

我认为我需要为此聚合添加选项{ read: :secondary }。但是我怎么能这样做呢?

如果我做一个简单的查询,我可以像这样添加{ read: :secondary }选项:

User.extras(read: :secondary)
=> #<Mongoid::Criteria
  selector: {}
  options:  {:read=>:secondary}
  class:    User
  embedded: false>

我使用的是Mongoid 4.0.2

(此User.extras(read: :secondary).collection.aggregate无效)

1 个答案:

答案 0 :(得分:0)

您可以将read: { mode: :secondary }作为第二个参数传递给aggregate。例如:

User.collection.aggregate(
  [
    {
      '$group' => {
      'status' => '$status',
      'total' => { '$sum' => '$balance' }
    }
  ],
  read: { mode: :secondary }
)