Aggregation in MongoDB

Content Overview :

- What is Aggregation ?

What is Aggregation?

When it’s time to gather the metrics from MongoDB, maybe for some graphical representation or some other operation, there is no better technique than MongoDBaggregations.

Aggregation in MongoDB is an operation used to process the data that returns the computed results

Aggregation basically groups the data from multiple documents and operates in many ways on those grouped data in order to return one combined result.

It processes documents and return computed results and can perform a variety of operations on the grouped data to return a single result.

To read more about this Pipeline process their beautiful official documentation page.

Following is the syntax for aggregation :

db.collection_name.aggregate(aggregate_operation)

The examples use a collection named Player with the following documents:

{ "_id" : ObjectId("5d7f771ed0cad9b461a1ba67"), "player" : "pyr1", "score" : 2, "team" : "a" }
{ "_id" : ObjectId("5d7f771ed0cad9b461a1ba68"), "player" : "pyr2", "score" : 1, "team" : "b" }
{ "_id" : ObjectId("5d7f771ed0cad9b461a1ba69"), "player" : "pyr3", "score" : 3, "team" : "c" }
{ "_id" : ObjectId("5d7f771ed0cad9b461a1ba6d"), "player" : "pyr7", "score" : 0, "team" : "a" }
{ "_id" : ObjectId("5d7f771ed0cad9b461a1ba6e"), "player" : "pyr8", "score" : 3, "team" : "b" }

Now, from the above collection, let us use the aggregate function to match the team which is of the team b and score greater than 2. The following command will be used :

db.myCollection.aggregate([{$match: {
'team':'b',
score:{
$gt:2
}
}}])

output:

{ "_id" : ObjectId("5d7f771ed0cad9b461a1ba6e"), "player" : "pyr8", "score" : 3, "team" : "b" }

Different expressions used by Aggregate function

ExpressionDescription
$sumSummates the defined values from all the documents in a collection
$avgCalculates the average values from all the documents in a collection
$minReturn the minimum of all values of documents in a collection
$maxReturn the maximum of all values of documents in a collection
$addToSetInserts values to an array but no duplicates in the resulting document
$pushInserts values to an array in the resulting document
$firstReturns the first document from the source document
$lastReturns the last document from the source document

2 thoughts on “Aggregation in MongoDB”

Leave a Comment

Your email address will not be published. Required fields are marked *