Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid `group()` conditions

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?

like image 595
JP Silvashy Avatar asked Oct 10 '22 01:10

JP Silvashy


1 Answers

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

like image 100
Russell Avatar answered Oct 15 '22 17:10

Russell