我想为我在 Mongoid 中的分组提供一个条件,但是如何为条件哈希中的一个属性发送多个值?这就是我想做的:
PageViews.collection.group(
cond: {page_id: ['4e6912618083ab383e000010', '4e6912618083ab383e000009']},
key: 'timestamp',
initial: {count: 0},
reduce: "function(x, y) {y.count += x.count;}"
)
因此,任何带有 page_id
的 PageView
都将是查询的一部分,但我似乎无法获得条件哈希 (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).
那么如果它需要一个 String
或 BSON::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/