Aggregate with Mongoid

neon picture neon · Aug 30, 2012 · Viewed 19.1k times · Source

MongoDB has a new Aggregation Framework and I'm trying to figure out how to use it with Mongoid. It appears there is a branch of Moped with this functionality as discussed here. I've updated to MongoDB 2.2 and tried installing this branch of Moped on my app like this:

gem 'moped', git: 'git://github.com/mongoid/moped.git', branch: 'aggregation-support'

but aggregation is still not working. This is the call I am using to test it:

= Post.all.aggregate({ "$group" => { "_id" => "$_id" } })

UPDATE

In the mongo shell this works:

db.users.aggregate({ $group : { _id : "$_id" }})

so I'm thinking it's a Mongoid issue...any word on this would be great!

Answer

yacc picture yacc · Mar 21, 2013

Since 3.0.1, Mongoid requires MongoDB 2.2 and supports the new aggregation framework.

You can now call aggregate on collections:

project = {"$project" => 
  {
    "charges" => 1,
    "year"    => { "$year" => "$created"}, "month" => { "$month" => "$created"},
    "week"    => { "$week" => "$created"}, "day"   => { "$dayOfYear" => "$created"} 
  }
}
group =  { "$group" =>
  { "_id" => {"year"=>"$year", "week"=>"$week"}, "count" => { "$sum" => 1 } } 
}
Charge.collection.aggregate([project,group])