How to MongoDB- Record Aggregation

In this guide, we are learning about aggregation of MongoDB records.

Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together and can perform a variety of operations on the grouped data to return a single result.

Syntax:
    db.collection.aggregate(pipeline, options)

 

Calculates aggregate values for the data in a collection.

ParameterTypeDescription
pipelinearrayA sequence of data aggregation operations or stages. See the aggregation pipeline operators for details.
Changed in version 2.6: The method can still accept the pipeline stages as separate arguments instead of as elements in an array; however, if you do not specify the pipeline as an array, you cannot specify the options parameter.
optionsdocumentOptional. Additional options that aggregate() passes to the aggregate command.

 

Example:
    {"_id" : ObjectId(3645369881331adf45ece), "course": "MySQL",  "category": "Database", "by": "lauyou" },
    {"_id" : ObjectId(3645369881331adf45ecd), "course": "MongoDB", "category": "Database", "by": "lauyou.com" },
    {"_id" : ObjectId(3645369881331adf45ecf), "course": "Java", "category": "Programming language", "by": "lauyou.com"}

 

To display a list stating how many courses includes in each category, we use the aggregate() method.

Sample code
    > db.mycollection.aggregate([{$group : {_id : "$category", num_courses : {$sum : 1}}}])
    {
       "result" : [
          {
             "_id" : "Database",
             "num_courses" : 2
          },
          {
             "_id" : "Programming language",
             "num_courses" : 1
          }
       ],
      "ok" : 1
    }

 

The list of available aggregation expressions.

ExpressionDescription
$sumSums up the defined value from all documents in the collection.
$avgCalculates the average of all given values from all documents in the collection.
$minGets the minimum of the corresponding values from all documents in the collection.
$maxGets the maximum of the corresponding values from all documents in the collection.
$pushInserts the value to an array in the resulting document.
$addToSetInserts the value to an array in the resulting document but does not create duplicates.
$firstGets the first document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.
$lastGets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.

 

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...