-
Notifications
You must be signed in to change notification settings - Fork 0
07‐Aggregation
-
Aggregation: Collection and summary of data -
Stage: One of the built-in methods that can be completed on the data, but does not permanently alter it -
Aggregation pipeline: A series of stages completed on the data in order
Structure of an Aggregation Pipeline
db.collection.aggregate([
{
$stage1: {
{ expression1 },
{ expression2 }...
},
$stage2: {
{ expression1 }...
}
}
])The $match stage filters for documents that match specified conditions. Here's the code for $match:
{
$match: {
"field_name": "value"
}
}The $group stage groups documents by a group key.
{
$group:
{
_id: <expression>, // Group key
<field>: { <accumulator> : <expression> }
}
}The following aggregation pipeline finds the documents with a field named "state" that matches a value "CA" and then groups those documents by the group key "$city" and shows the total number of zip codes in the state of California.
db.zips.aggregate([
{
$match: {
state: "CA"
}
},
{
$group: {
_id: "$city",
totalZips: { $count : { } }
}
}
])The $sort stage sorts all input documents and returns them to the pipeline in sorted order. We use 1 to represent ascending order, and -1 to represent descending order.
{
$sort: {
"field_name": 1
}
}The $limit stage returns only a specified number of records.
{
$limit: 5
}The following aggregation pipeline sorts the documents in descending order, so the documents with the greatest pop value appear first, and limits the output to only the first five documents after sorting.
db.zips.aggregate([
{
$sort: {
pop: -1
}
},
{
$limit: 5
}
])Review the following sections, which show the code for the $project, $set, and $count aggregation stages.
The $project stage specifies the fields of the output documents. 1 means that the field should be included, and 0 means that the field should be supressed. The field can also be assigned a new value.
{
$project: {
state:1,
zip:1,
population:"$pop",
_id:0
}
}The $set stage creates new fields or changes the value of existing fields, and then outputs the documents with the new fields.
{
$set: {
place: {
$concat:["$city",",","$state"]
},
pop:10000
}
}The $count stage creates a new document, with the number of documents at that stage in the aggregation pipeline assigned to the specified field name.
{
$count: "total_zips"
}