- Aggregation >
- Aggregation Framework Examples
Aggregation Framework Examples¶
On this page
MongoDB provides flexible data aggregation functionality with the
aggregate command. For additional information about
aggregation consider the following resources:
This document provides a number of practical examples that display the capabilities of the aggregation framework. All examples use a publicly available data set of all zipcodes and populations in the United States.
Aggregations using the Zip Code Data Set¶
To run you will need the zipcode data set. These data are available at:
media.mongodb.org/zips.json.
Use mongoimport to load this data set into your
mongod instance.
Data Model¶
Each document in this collection has the following form:
In these documents:
- The
_idfield holds the zipcode as a string. - The
cityfield holds the city. - The
statefield holds the two letter state abbreviation. - The
popfield holds the population. - The
locfield holds the location as a latitude longitude pair.
All of the following examples use the aggregate() helper in the mongo
shell. aggregate() provides a
wrapper around the aggregate database command. See the
documentation for your driver for a
more idiomatic interface for data aggregation operations.
States with Populations Over 10 Million¶
To return all states with a population greater than 10 million, use the following aggregation operation:
Aggregations operations using the aggregate() helper, process all documents on the
zipcodes collection. aggregate() connects a number of pipeline operators, which define the aggregation
process.
In the above example, the pipeline passes all documents in the
zipcodes collection through the following steps:
the
$groupoperator collects all documents and creates documents for each state.These new per-state documents have one field in addition the
_idfield:totalPopwhich is a generated field using the$sumoperation to calculate the total value of allpopfields in the source documents.After the
$groupoperation the documents in the pipeline resemble the following:the
$matchoperation filters these documents so that the only documents that remain are those where the value oftotalPopis greater than or equal to 10 million.The
$matchoperation does not alter the documents, which have the same format as the documents output by$group.
The equivalent SQL for this operation is:
Average City Population by State¶
To return the average populations for cities in each state, use the following aggregation operation:
Aggregations operations using the aggregate() helper, process all documents on the
zipcodes collection. aggregate() a number of pipeline operators that define the aggregation
process.
In the above example, the pipeline passes all documents in the
zipcodes collection through the following steps:
the
$groupoperator collects all documents and creates new documents for every combination of thecityandstatefields in the source document.After this stage in the pipeline, the documents resemble the following:
the second
$groupoperator collects documents by thestatefield and use the$avgexpression to compute a value for theavgCityPopfield.
The final output of this aggregation operation is:
Largest and Smallest Cities by State¶
To return the smallest and largest cities by population for each state, use the following aggregation operation:
Aggregations operations using the aggregate() helper, process all documents on the
zipcodes collection. aggregate() a number of pipeline operators that define the aggregation
process.
All documents from the zipcodes collection pass into the pipeline,
which consists of the following steps:
the
$groupoperator collects all documents and creates new documents for every combination of thecityandstatefields in the source documents.By specifying the value of
_idas a sub-document that contains both fields, the operation preserves thestatefield for use later in the pipeline. The documents produced by this stage of the pipeline have a second field,pop, which uses the$sumoperator to provide the total of thepopfields in the source document.At this stage in the pipeline, the documents resemble the following:
$sortoperator orders the documents in the pipeline based on the value of thepopfield from smallest to largest. This operation does not alter the documents.the second
$groupoperator collects the documents in the pipeline by thestatefield, which is a field inside the nested_iddocument.Within each per-state document this
$groupoperator specifies four fields: Using the$lastexpression, the$groupoperator creates thebiggestcityandbiggestpopfields that store the city with the largest population and that population. Using the$firstexpression, the$groupoperator creates thesmallestcityandsmallestpopfields that store the city with the smallest population and that population.The documents, at this stage in the pipeline resemble the following:
The final operation is
$project, which renames the_idfield tostateand moves thebiggestCity,biggestPop,smallestCity, andsmallestPopintobiggestCityandsmallestCitysub-documents.
The final output of this aggregation operation is:
Aggregation with User Preference Data¶
Data Model¶
Consider a hypothetical sports club with a database that contains a
user collection that tracks user’s join dates, sport preferences,
and stores these data in documents that resemble the following:
Normalize and Sort Documents¶
The following operation returns user names in upper case and in
alphabetical order. The aggregation includes user names for all documents in
the users collection. You might do this to normalize user names for
processing.
All documents from the users collection passes through the
pipeline, which consists of the following operations:
The results of the aggregation would resemble the following:
Return Usernames Ordered by Join Month¶
The following aggregation operation returns user names sorted by the month they joined. This kind of aggregation could help generate membership renewal notices.
The pipeline passes all documents in the users collection through
the following operations:
- The
$projectoperator:- Creates two new fields:
month_joinedandname. - Suppresses the
idfrom the results. Theaggregate()method includes the_id, unless explicitly suppressed.
- Creates two new fields:
- The
$monthoperator converts the values of thejoinedfield to integer representations of the month. Then the$projectoperator assigns those values to themonth_joinedfield. - The
$sortoperator sorts the results by themonth_joinedfield.
The operation returns results that resemble the following:
Return Total Number of Joins per Month¶
The following operation shows how many people joined each month of the year. You might use this aggregated data for such information for recruiting and marketing strategies.
The pipeline passes all documents in the users collection through
the following operations:
- The
$projectoperator creates a new field calledmonth_joined. - The
$monthoperator converts the values of thejoinedfield to integer representations of the month. Then the$projectoperator assigns the values to themonth_joinedfield. - The
$groupoperator collects all documents with a givenmonth_joinedvalue and counts how many documents there are for that value. Specifically, for each unique value,$groupcreates a new “per-month” document with two fields:_id, which contains a nested document with themonth_joinedfield and its value.number, which is a generated field. The$sumoperator increments this field by 1 for every document containing the givenmonth_joinedvalue.
- The
$sortoperator sorts the documents created by$groupaccording to the contents of themonth_joinedfield.
The result of this aggregation operation would resemble the following:
Return the Five Most Common “Likes”¶
The following aggregation collects top five most “liked” activities in the data set. In this data set, you might use an analysis of this to help inform planning and future development.
The pipeline begins with all documents in the users collection,
and passes these documents through the following operations:
The
$unwindoperator separates each value in thelikesarray, and creates a new version of the source document for every element in the array.Example
Given the following document from the
userscollection:The
$unwindoperator would create the following documents:The
$groupoperator collects all documents the same value for thelikesfield and counts each grouping. With this information,$groupcreates a new document with two fields:_id, which contains thelikesvalue.number, which is a generated field. The$sumoperator increments this field by 1 for every document containing the givenlikesvalue.
The
$sortoperator sorts these documents by thenumberfield in reverse order.The
$limitoperator only includes the first 5 result documents.
The results of aggregation would resemble the following: