Aggregation operations groups of values from multiple documents, and returns a single value on the grouped data.
In SQL, avg, sum and count functions are all examples of aggregate operations.
To do aggregation in MongoDB, use aggregate() method.
The basic syntax of aggregate() method is as follows
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
To get how many tutorials are written by each user, use aggregate() method as shown below:
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
>
The following table lists aggregation expressions.
Expression | Description | Example |
---|---|---|
$sum | Sums value. | db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$comments"}}}]) |
$avg | Calculates the average. | db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$comments"}}}]) |
$min | Gets the minimum of the corresponding values from all documents in the collection. | db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$comments"}}}]) |
$max | Gets the maximum of the values. | db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$comments"}}}]) |
$push | Inserts the value to an array in the resulting document. | db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}]) |
$addToSet | Inserts the value to an array in the resulting document without creating duplicates. | db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}]) |
$first | Gets the first document from the source documents according to the grouping. | db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}]) |
$last | Gets the last document from the source documents according to the grouping. | db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}]) |
In MongoDB we can execute an operation on some documents and use the output as the input for the next command and so on.
We can use the following operations in Pipeline operation.