## 7.3.1 Aggregation with the Zip Code Data Set 

The examples in this document use the zipcodes collection. This collection is available at: me- dia.mongodb.org/zips.json$^{13}$. Use mongoimport to load this data set into your mongod instance. 

## Data Model 

Each document in the zipcodes collection has the following form: 

{ "_id": "10280", "city": "NEW YORK", "state": "NY", "pop": 5574, "loc": [ -74.016323, 40.710537 ] } 

• The _id field holds the zip code as a string. 

• The city field holds the city name. A city can have more than one zip code associated with it as different sections of the city can each have a different zip code. 

• The state field holds the two letter state abbreviation. 

• The pop field holds the population. 

• The loc field holds the location as a latitude longitude pair. 

## aggregate() Method 

All of the following examples use the aggregate() helper in the mongo shell. 

The aggregate() method uses the aggregation pipeline (page 440) to processes documents into aggregated results. An aggregation pipeline (page 440) consists of stages with each stage processing the documents as they pass along the pipeline. Documents pass through the stages in sequence. 

The aggregate() method in the mongo shell provides a wrapper around the aggregate database command. See the documentation for your driver for a more idiomatic interface for data aggregation operations. 

## Return States with Populations above 10 Million 

The following aggregation operation returns all states with total population greater than 10 million: 

db.zipcodes.aggregate( [ { $group: { _id: "$state", totalPop: { $sum: "$pop" } } }, { $match: { totalPop: { $gte: 10 * 1000 * 1000 } } } ] ) 

In this example, the aggregation pipeline (page 440) consists of the $group stage followed by the $match stage: 

• The $group stage groups the documents of the zipcode collection by the state field, calculates the totalPop field for each state, and outputs a document for each unique state. 

