ruby-on-rails - Mongoid `group()` 条件

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

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

因此,任何带有 page_idPageView 都将是查询的一部分,但我似乎无法获得条件哈希 (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;}"
)

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

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>'

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

(String, BSON::Code) :cond — default: {} — A document specifying a query for filtering the documents over which the aggregation is run (optional).

那么如果它需要一个 StringBSON::Code,这会是什么样子?

最佳答案

您需要使用 $in 进行查询以匹配多个值。所以应该写成

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

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

关于ruby-on-rails - Mongoid `group()` 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7354851/

相关文章:

php - 将数据从关系数据库反规范化到非关系数据库的最佳实践

python - Python中的跟踪系统和实时统计分析

mongodb - 如何使用 map/reduce 处理 10000 多个唯一键以在 MongoDB

javascript - 查找和更新嵌套级别

mongodb - 在 MongoDB 中使用 directoryperdb 的好处

mongodb安装 - 要求?

mongodb - mongodb中OR+Sort查询的复合索引

python - 如何使用 MongoKit 对远程数据库主机进行身份验证?

python - Pymongo 断言错误 : ids don't match

mongodb - 您将如何使用文档存储(例如 CouchDB、Redis、MongoDB、Riak