17
votes

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!

2
Is it because on the shell you are accessing the users collection and in Mongoid the posts collection? ^^ - Christoph Geschwind
Have you tried Post.collection.aggregate("$group" => { "_id" => "$_id" }) ? - Christoph Geschwind
@neon did you get the aggregate framework to work with moped and mongoid using that branch and would you like to update your question with the solution. - brg
It seems like you're missing the aggregation function in your update? Are you trying to sum, find a min or a max or what? In any case, in Mongoid 3.0.x the aggregation methods "avg", "max", "min", and "sum" are documented here: mongoid.org/en/mongoid/docs/querying.html#aggregations - GSP

2 Answers

31
votes

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])
13
votes

At this time, mongoid provides no additional syntax beyond what Moped exposes. If you're willing to include Moped (pointed to master) in your Gemfile, you can test out Moped's support for aggregate.

gem 'moped', :git => 'git://github.com/mongoid/moped.git'

You'll want to remember to pull this once 1.3.0 is released, and just update via the normal route of gem update moped.

With that in place, you can run your query with:

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

See the Moped changelog for more information.