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!
As with many other database systems, MongoDB allows you to perform a variety of aggregation operations. These allow you to process data records in a variety of ways, such as grouping data, sorting data into a specific order, or restructuring returned documents, as well as filtering data as one might with a query.
Mongoose's aggregate() function returns an instance of Mongoose's Aggregate class. Aggregate instances are thenable, so you can use them with await and promise chaining. The Aggregate class also supports a chaining interface for building aggregation pipelines.
An aggregation pipeline consists of one or more stages that process documents: Each stage performs an operation on the input documents. For example, a stage can filter documents, group documents, and calculate values. The documents that are output from a stage are passed to the next stage.
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])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With