aggregate() - Retrieve JSON documents command
Runs a sequence of tasks to retrieve documents from a collection, including attributes and calculated values. Tasks can occur multiple times.
Syntax diagram
Command parameters
- task
- This parameter specifies one or more of the following options:
- $distinct
- Retrieves distinct values for specific fields.
- $group
- Sets a grouping key and collects grouped values.
- $limit
- Returns at most the specified number of documents from the result set.
- $match
- Filters documents.
- $project
- Selects fields for the document to retrieve. You can specify fields to include, not exclude.
- $skip
- Skips the specified number of documents.
- $sort
- Sorts the data on the specified fields.
- $unwind
- Returns a stream of individual documents from the elements of an array.
Example
Calculate the average price of books
per author in a category.
db.books.aggregate(
{$match: { category: "Fantasy" }},
{$project: {author:1, price:1}},
{$group: {_id: {author:1}, avgPrice:{$avg:"$price"}}}
)Sample output that is as follows:Row 1:
{
"_id":"Tolkien, J.R",
"avgPrice":15.5
}
Row 2:
{
"_id":"Verne, Jules",
"avgPrice":6.35
}
2 rows returned 