Aggregation in MongoDB
Aggregation in MongoDB is nothing but 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. In sql
count(*)
and with group by is an equivalent of MongoDB aggregation.
Aggregate function groups the records in a collection, and can be used to provide total number(sum), average, minimum, maximum etc out of the group selected.
In order to perform the aggregate function in MongoDB,
aggregate ()
is the function to be used. Following is the syntax for aggregation :db.collection_name.aggregate(aggregate_operation)
Let us now see how to make use of the aggregate function in MongoDB. Consider a collection named books with the data as shown below :
NOTE : Create a collection named books, with fieldnames - title, price and type. Use
db.books.find()
to list down the contents of the collection.
Now, from the above collection, let us use the aggregate function to group the books which are of the type ebook and online. Following command will be used :
db.books.aggregate([{$group : {_id: "$type", category: {$sum : 1}}}])
The above aggregate function will give result, which says there are 2 records of the type ebook and 2 records of the type online. So the above aggregation command, has grouped our collection data, based on their type.
Different expressions used by Aggregate function
Expression | Description |
---|---|
$sum | Summates the defined values from all the documents in a collection |
$avg | Calculates the average values from all the documents in a collection |
$min | Return the minimum of all values of documents in a collection |
$max | Return the maximum of all values of documents in a collection |
$addToSet | Inserts values to an array but no duplicates in the resulting document |
$push | Inserts values to an array in the resulting document |
$first | Returns the first document from the source document |
$last | Returns the last document from the source document |
No comments:
Post a Comment