OPTIONS
翻译或纠错本页面

aggregate

aggregate

2.2 新版功能.

Performs aggregation operation using the aggregation pipeline. The pipeline allows users to process data from a collection with a sequence of stage-based manipulations.

在 2.6 版更改.

  • The aggregate command adds support for returning a cursor, supports the explain option, and enhances its sort operations with an external sort facility.
  • aggregation pipeline introduces the $out operator to allow aggregate command to store results to a collection.

The command has following syntax:

在 2.6 版更改.

{
  aggregate: "<collection>",
  pipeline: [ <stage>, <...> ],
  explain: <boolean>,
  allowDiskUse: <boolean>,
  cursor: <document>
}

The aggregate command takes the following fields as arguments:

Field Type Description
aggregate string The name of the collection to as the input for the aggregation pipeline.
pipeline array An array of aggregation pipeline stages that process and transform the document stream as part of the aggregation pipeline.
explain boolean

Optional. Specifies to return the information on the processing of the pipeline.

2.6 新版功能.

allowDiskUse boolean

Optional. Enables writing to temporary files. When set to true, aggregation stages can write data to the _tmp subdirectory in the dbPath directory.

2.6 新版功能.

cursor document

Optional. Specify a document that contains options that control the creation of the cursor object.

2.6 新版功能.

For more information about the aggregation pipeline 聚合管道, Aggregation Reference, and 聚合管道的限制.

Example

Aggregate Data with Multi-Stage Pipeline

A collection articles contains documents such as the following:

{
   _id: ObjectId("52769ea0f3dc6ead47c9a1b2"),
   author: "abc123",
   title: "zzz",
   tags: [ "programming", "database", "mongodb" ]
}

The following example performs an aggregate operation on the articles collection to calculate the count of each distinct element in the tags array that appears in the collection.

db.runCommand(
   { aggregate: "articles",
     pipeline: [
                 { $project: { tags: 1 } },
                 { $unwind: "$tags" },
                 { $group: {
                             _id: "$tags",
                             count: { $sum : 1 }
                           }
                 }
               ]
   }
)

In the mongo shell, this operation can use the aggregate() helper as in the following:

db.articles.aggregate(
                       [
                          { $project: { tags: 1 } },
                          { $unwind: "$tags" },
                          { $group: {
                                      _id: "$tags",
                                      count: { $sum : 1 }
                                    }
                          }
                       ]
)

注解

In 2.6 and later, the aggregate() helper always returns a cursor.

在 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.

Return Information on the Aggregation Operation

The following aggregation operation sets the optional field explain to true to return information about the aggregation operation.

db.runCommand( { aggregate: "orders",
                 pipeline: [
                             { $match: { status: "A" } },
                             { $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
                             { $sort: { total: -1 } }
                           ],
                 explain: true
              } )

注解

The intended readers of the explain output document are humans, and not machines, and the output format is subject to change between releases.

Aggregate Data using External Sort

Aggregation pipeline stages have maximum memory use limit. To handle large datasets, set allowDiskUse option to true to enable writing data to temporary files, as in the following example:

db.runCommand(
   { aggregate: "stocks",
     pipeline: [
                 { $project : { cusip: 1, date: 1, price: 1, _id: 0 } },
                 { $sort : { cusip : 1, date: 1 } }
               ],
     allowDiskUse: true
   }
)

Aggregate Command Returns a Cursor

注解

Using the aggregate command to return a cursor is a low-level operation, intended for authors of drivers. Most users should use the db.collection.aggregate() helper provided in the mongo shell or in their driver. In 2.6 and later, the aggregate() helper always returns a cursor.

The following command returns a document that contains results with which to instantiate a cursor object.

db.runCommand(
   { aggregate: "records",
     pipeline: [
        { $project: { name: 1, email: 1, _id: 0 } },
        { $sort: { name: 1 } }
     ],
     cursor: { }
   }
)

To specify an initial batch size, specify the batchSize in the cursor field, as in the following example:

db.runCommand(
   { aggregate: "records",
     pipeline: [
        { $project: { name: 1, email: 1, _id: 0 } },
        { $sort: { name: 1 } }
     ],
     cursor: { batchSize: 0 }
   }
)

The {batchSize: 0 } document specifies the size of the initial batch size only. Specify subsequent batch sizes to OP_GET_MORE operations as with other MongoDB cursors. A batchSize of 0 means an empty first batch and is useful if you want to quickly get back a cursor or failure message, without doing significant server-side work.