Reputation: 2821
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!
Upvotes: 18
Views: 21974
Reputation: 1118
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])
Upvotes: 32
Reputation: 1469
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.
Upvotes: 13