Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MongoDB Aggregation

MongoDB Aggregation

Aggregation (aggregate) in MongoDB is mainly used to process data (such as calculating averages, sums, etc.) and return computed data results.

Somewhat similar to SQL count(*) in a statement.


The aggregate() Method

Aggregation in MongoDB uses aggregate().

Syntax

The basic syntax of the aggregate() method is as follows:



>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

Example

The data in the collection is as follows:



{

   _id: ObjectId(7df78ad8902c)

   title: 'MongoDB Overview', 

   description: 'MongoDB is no sql database',

   by_user: 'runoob.com',

   url: 'http://www.runoob.com',

   tags: ['mongodb', 'database', 'NoSQL'],

   likes: 100

},

{

   _id: ObjectId(7df78ad8902d)

   title: 'NoSQL Overview', 

   description: 'No sql database is very fast',

   by_user: 'runoob.com',

   url: 'http://www.runoob.com',

   tags: ['mongodb', 'database', 'NoSQL'],

   likes: 10

},

{

   _id: ObjectId(7df78ad8902e)

   title: 'Neo4j Overview', 

   description: 'Neo4j is no sql database',

   by_user: 'Neo4j',

   url: 'http://www.neo4j.com',

   tags: ['neo4j', 'database', 'NoSQL'],

   likes: 750

},

Now we calculate the number of articles written by each author from the above collection, using aggregate() as follows:



> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])

{

   "result" : [

      {

         "_id" : "runoob.com",

         "num_tutorial" : 2

      },

      {

         "_id" : "Neo4j",

         "num_tutorial" : 1

      }

   ],

   "ok" : 1

}

>

The above example is similar to the sql statement:

 select by_user, count(*) from mycol group by by_user

In the above example, we group the data by the by_user field and calculate the sum for the same values of the by_user field.

The following table shows some aggregation expressions:

Expression Description Example
$sum Compute the total. db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])
$avg Compute an average db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
$min Gets the minimum value of the corresponding field across all documents in the collection. db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])
$max Gets the maximum value of the corresponding field across all documents in the collection. db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])
$push Adds values into an array without checking for duplicate values. db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])
$addToSet Adds values into an array, checking for duplicate values; if the same value already exists in the array, it is not added. db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])
$first Get the first document based on the order of the resource documents. db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])
$last Get the last document based on the order of the resource documents db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])

The concept of pipelines

In Unix and Linux, pipelines are generally used to pass the output of the current command as the argument to the next command.

MongoDB's aggregation pipeline passes MongoDB documents to the next stage after one stage of processing is complete. Pipeline operations can be repeated.

Expressions: process input documents and output. Expressions are stateless and can only be used to compute documents in the current aggregation pipeline, not to process other documents.

Here we introduce several commonly used operations in the aggregation framework:

Pipeline operator examples

1. $project example



db.article.aggregate(

    { $project : {

        title : 1 ,

        author : 1 ,

    }}

 );

In this way, the result will only have the three fields _id, tilte, and author. By default, the _id field is included. If you want to exclude _id, you can do this:



db.article.aggregate(

    { $project : {

        _id : 0 ,

        title : 1 ,

        author : 1

    }});

2. $match example



db.articles.aggregate( [

                        { $match : { score : { $gt : 70, $lte : 90 } } },

                        { $group: { _id: null, count: { $sum: 1 } } }

                       ] );

$match is used to get records with scores greater than 70 and less than or equal to 90, then send the qualifying records to the next stage, the $group pipeline operator, for processing.

3. $skip example



db.article.aggregate(

    { $skip : 5 });



After processing by the $skip pipeline operator, the first five documents are "filtered" out.