Welcome to a tutorial on Aggregation in MongoDB.
In MongoDB, Aggregation is an operation used to process the data that returns the computed results. Also, it groups the data from multiple documents and operates in many ways on those grouped data for it to return one combined result. In aggregation, the count(*) and with the group by is an equivalent of MongoDB aggregation.
In addition, the Aggregate function groups the records in a collection, and can be used to provide the total number (or sum), average, minimum, maximum, and so on, out of the group selected.
In MongoDB, to perform the aggregate function, the aggregate () is the function to be used. Below is the syntax for aggregation:
db.collection_name.aggregate(aggregate_operation)
Now, let’s see how to make use of the aggregate function in MongoDB. We will consider a collection named books with the data. This is shown below:
But, note that to create a collection named books, with fieldnames - title, price, and type. You should use db.books.find() to list down the contents of the collection.
From the collection above, we will use the aggregate function to group the books which are of the type ebook and online. You can use the command below:
db.books.aggregate([{$group : {_id: "$type", category: {$sum : 1}}}])
From the function above, we will have a result that says that there are 2 records of the type ebookand 2 records of the type online. Thus, the command above has grouped our collection data, based on their type.
Expression | Description |
$sum | It summates the defined values from all the documents in a collection |
$avg | This calculates the average values from all the documents in a collection |
$min | This returns the minimum of all values of documents in a collection |
$max | This returns the maximum of all values of documents in a collection |
$addToSet | This inserts values to an array but no duplicates in the resulting document |
$push | This inserts values to an array in the resulting document |
$first | It returns the first document from the source document |
$last | This returns the last document from the source document |