Navigation
This version of the documentation is archived and no longer supported.

db.collection.aggregate()

On this page

Definition

db.collection.aggregate(pipeline)

New in version 2.2.

Calculates aggregate values for the data in a collection. Always call the aggregate() method on a collection object.

Parameter Type Description
pipeline document A sequence of data aggregation processes. See the aggregation reference for documentation of these operators.
Returns:A document with two fields:
  • result which holds an array of documents returned by the pipeline
  • ok which holds the value 1, indicating success.
Throws:exception

Changed in version 2.4: If an error occurs, the aggregate() helper throws an exception. In previous versions, the helper returned a document with the error message and code, and ok status field not equal to 1, same as the aggregate command.

Example

Consider a collection named articles that contains documents of the following format:

{
  title : "this is my title" ,
  author : "bob" ,
  posted : new Date () ,
  pageViews : 5 ,
  tags : [ "fun" , "good" , "sport" ] ,
  comments : [
               { author :"joe" , text : "this is cool" } ,
               { author :"sam" , text : "this is bad" }
  ],
  other : { foo : 5 }
}

The following aggregation pivots the data to group authors by individual tags:

db.articles.aggregate(
  { $project : {
                 author : 1,
                 tags : 1,
               }
  },
  { $unwind : "$tags" },
  { $group : {
               _id : { tags : "$tags" },
               authors : { $addToSet : "$author" }
             }
  }
)

The aggregation pipeline begins with the collection articles and selects the author and tags fields using the $project pipeline operator. The $unwind operator produces one output document per tag. Finally, the $group pipeline operator groups authors by tags.

The operation returns the following document:

{
   "result" : [
                {
                  "_id" : { "tags" : "good" },
                  "authors" : [ "bob", "mike", ... ]
                },
                {
                  "_id" : { "tags" : "fun" },
                  "authors" : [ "bob", "al" ]
                },

                ...

              ],
   "ok" : 1
}

The returned document contains two fields:

  • result field, which holds an array of documents returned by the pipeline, and
  • ok field, which holds the value 1, indicating success.

For more information, see Aggregation Concepts, Aggregation Reference, and aggregate.