Conditions Mongoid `group ()`

I want to provide a condition for my grouping in Mongoid, but how can I send multiple values ​​for an attribute to hash conditions? 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;}" ) 

This way, any PageView with either page_id will be separated from the request, but I cannot make the hash ( cond ) condition work at all! What I'm doing wrong here, I'm really confused.

Here are 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;}" ) 

It returns the following error, but the syntax looks good 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 is frustrating that there are no examples of this anywhere, the docs say that the condition parameter is this:

(String, BSON :: Code): cond - default: {} - a document indicating the request for filtering documents by which aggregation is performed (Optional).

So, if it accepts String or BSON::Code , what would it look like?

+5
source share
1 answer

You need to use $in so that the query matches 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 this here: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24in

+4
source

All Articles