- Reference >
mongoShell Methods >- Collection Methods >
- db.collection.aggregate()
db.collection.aggregate()¶
On this page
Definition¶
-
db.collection.aggregate(pipeline)¶ New in version 2.2.
Calculates aggregate values for the data in a collection. Always call the
aggregate()method on a collection object.Parameter Type Description pipelinedocument A sequence of data aggregation processes. See the aggregation reference for documentation of these operators. Returns: A document with two fields: resultwhich holds an array of documents returned by the pipelineokwhich holds the value1, indicating success.
Throws: exception – Changed in version 2.4: If an error occurs, the
aggregate()helper throws an exception. In previous versions, the helper returned a document with the error message and code, andokstatus field not equal to1, same as theaggregatecommand.
Example¶
Consider a collection named articles that contains documents of the
following format:
The following aggregation pivots the data to group authors by individual tags:
The aggregation pipeline begins with the collection articles and
selects the author and tags fields using the
$project pipeline operator. The $unwind
operator produces one output document per tag. Finally, the
$group pipeline operator groups authors by tags.
The operation returns the following document:
The returned document contains two fields:
resultfield, which holds an array of documents returned by the pipeline, andokfield, which holds the value1, indicating success.
For more information, see Aggregation Concepts,
Aggregation Reference, and aggregate.