Mongoid`group()`条件

JP *_*shy 5 ruby ruby-on-rails mongodb mongoid

我想为Mongoid中的分组提供条件,但是如何在条件哈希中为属性发送多个值?这就是我想要做的:

PageViews.collection.group(
  cond: {page_id: ['4e6912618083ab383e000010', '4e6912618083ab383e000009']},
  key: 'timestamp',
  initial: {count: 0},
  reduce: "function(x, y) {y.count += x.count;}"
)
Run Code Online (Sandbox Code Playgroud)

所以任何PageView一个都page_id将是查询的一部分,但我似乎无法让条件hash(cond)完全工作!我在这里做错了什么,我真的很困惑.

以下是该group()方法的API文档:http://api.mongodb.org/ruby/current/Mongo/Collection.html#group-instance_method

任何帮助将不胜感激.


更新

像这样运行查询:

PageViews.collection.group(
  cond: {page_id: { $in : ['4e6912618083ab383e000010', '4e6912618083ab383e000009']}},
  key: 'timestamp',
  initial: {count: 0},
  reduce: "function(x, y) {y.count += x.count;}"
)
Run Code Online (Sandbox Code Playgroud)

返回以下错误,但语法对我来说很好:

SyntaxError: (irb):170: syntax error, unexpected ':', expecting tASSOC
  cond: {page_id: { $in : ['4e6912618083ab383e000010',...
                         ^
(irb):170: syntax error, unexpected '}', expecting $end
...', '4e6912618083ab383e000009']}},
...                               ^
    from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/commands/console.rb:45:in `start'
    from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/commands/console.rb:8:in `start'
    from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/commands.rb:40:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'
Run Code Online (Sandbox Code Playgroud)

令人沮丧的是,在任何地方都没有这样的例子,文档说条件参数是这样的:

(String,BSON :: Code):cond - default:{} - 指定用于过滤运行聚合的文档的查询的文档(可选).

所以,如果它需要一个String或者BSON::Code,这将是什么样的?

Rus*_*ell 4

您需要使用$in查询来匹配多个值。所以它会写成

PageViews.collection.group(
  :cond => {:page_id => { '$in' => ['4e6912618083ab383e000010', '4e6912618083ab383e000009']}},
  :key => 'timestamp',
  :initial => {count: 0},
  :reduce => "function(x, y) {y.count += x.count;}"
)    
Run Code Online (Sandbox Code Playgroud)

您可以在这里阅读更多相关信息:http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24in