- Working With Data >
- Aggregation Pipeline
Aggregation Pipeline¶
Mongoid exposes MongoDB’s aggregation pipeline, which is used to construct flows of operations that process and return results. The aggregation pipeline is a superset of the deprecated map/reduce framework functionality.
Basic Usage¶
Querying Across Multiple Collections¶
The aggregation pipeline may be used for queries involving multiple referenced associations at the same time:
To retrieve bands that toured since 2000 and have at least one award, one could do the following:
Note that the aggregation pipeline, since it is implemented by the Ruby driver
for MongoDB and not Mongoid, returns raw BSON::Document
objects rather than
Mongoid::Document
model instances. The above example projects only
the _id
field which is then used to load full models. An alternative is
to not perform such a projection and work with raw fields, which would eliminate
having to send the list of document ids to Mongoid in the second query
(which could be large).
Builder DSL¶
Mongoid provides limited support for constructing the aggregation pipeline itself using a high-level DSL. The following aggregation pipeline operators are supported:
To construct a pipeline, call the corresponding aggregation pipeline methods
on a Criteria
instance. Aggregation pipeline operations are added to the
pipeline
attribute of the Criteria
instance. To execute the pipeline,
pass the pipeline
attribute value to Collection#aggragegate
method.
For example, given the following models:
We can find out which states a participant visited:
group¶
The group
method adds a $group aggregation pipeline stage.
The field expressions support Mongoid symbol-operator syntax:
Alternatively, standard MongoDB aggregation pipeline syntax may be used:
project¶
The project
method adds a $project aggregation pipeline stage.
The argument should be a Hash specifying the projection:
unwind¶
The unwind
method adds an $unwind aggregation pipeline stage.
The argument can be a field name, specifiable as a symbol or a string, or
a Hash or a BSON::Document
instance: