I want to provide a condition for my grouping in Mongoid, but how can I send in multiple values for an attribute in the conditions hash? This is what I want to do:
PageViews.collection.group(
cond: {page_id: ['4e6912618083ab383e000010', '4e6912618083ab383e000009']},
key: 'timestamp',
initial: {count: 0},
reduce: "function(x, y) {y.count += x.count;}"
)
So therefore any PageView
with the either page_id
will be apart of the query, but I can't seem to get the condition hash (cond
) to work at all! What am I doing wrong here, I'm really confused.
Here is the API docs for the group()
method: http://api.mongodb.org/ruby/current/Mongo/Collection.html#group-instance_method
Any help would be greatly appreciated.
update
Running the query as such:
PageViews.collection.group(
cond: {page_id: { $in : ['4e6912618083ab383e000010', '4e6912618083ab383e000009']}},
key: 'timestamp',
initial: {count: 0},
reduce: "function(x, y) {y.count += x.count;}"
)
Returns the following error, but the syntax looks fine to me:
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>'
It's frustrating that there are like no examples of this anywhere, the docs say that the condition parameter is as such:
(String, BSON::Code) :cond — default: {} — A document specifying a query for filtering the documents over which the aggregation is run (optional).
So if it takes a String
or BSON::Code
, what would this look like?
You need to use $in
for the query to match against multiple values. So it would be written as
PageViews.collection.group(
:cond => {:page_id => { '$in' => ['4e6912618083ab383e000010', '4e6912618083ab383e000009']}},
:key => 'timestamp',
:initial => {count: 0},
:reduce => "function(x, y) {y.count += x.count;}"
)
You can read more about it here: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24in
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With