MongoDB aggregate__ function of aggregate function

Source: Internet
Author: User

The use of aggregate helps us to further split the set in MongoDB.

Example:

Db.collection.aggregate (
    {$match: {x:1}, {
    limit:10},
    {$group: {_id: "$age"}}
);

Operator Introduction:

$project: Include, exclude, rename, and display fields

$match: Query, requires the same parameters as find ()

$limit: Limit the number of results

$skip: Ignore number of results

$sort: Sort results by the given fields

$group: Combining results by given expression

$unwind: Dividing embedded arrays into their own top-level files

============================================================

This is a data Model on the MongoDB website:

{"
  _id": "10280",//zipcode
  "City": "NEW YORK",//
  "state": "NY",//city abbreviation
  "Pop": 5574,//population
  "loc": [/Latitude and longitude
    -74.016323,
    40.710537
  ]
}



1. Find a city with more than 10 million people

Db.zipcodes.aggregate (
    {$group: {_id: "$state", totalpop:{$sum: "$pop"}},
    {$match: {totalpop:{$get : 10000000}}
);


The above statement is equivalent to: SELECT state, sum (POPs) Totalpop from ZipCodes Group by Totalpop >= 10000000;

Analysis:

$group is used primarily for grouping, where _id is a collection of groups of types, Totalpop is a new field generated that is used to store totals.

In fact, after the document has been $group, the system generates a new document for it (the new documment is {"_id": "AK", "Totalpop": 550043}), which we will see more clearly in the following example.

$match, which is equivalent to providing query functionality for the newly generated document

2, the average population, each state


db.zipcodes.aggregate {$group: {_id: {state
                         : ' $state ', City: ' $city '},
                           pop: {$sum: ' $pop '}}},
                       { $group:
                       {_id: "$_id.state",
                         avgcitypop: {$avg: "$pop"}}})


There are two $group in the example above, what does that mean?

The first $group is to turn the original ZipCodes document into a new one, such as:


{'
  _id ': {' state
    ': ' CO ',
    ' city ': ' Edgewater '
  },
  ' Pop ': 13154
}


The second $group is based on the original, again reformatting the data, and then generate a new document, such as:


{
  "_id": "MN",
  "Avgcitypop": 5335
},

3. Check the largest and smallest cities in each state


Db.zipcodes.aggregate (
	{$group: {_id:{state: "$state", City: "$city"}, totalpop:{$sum: "$pop"}}},//the people of the statistical State, Generate a new document about the state and its total population
	{$sort: {"Totalpop": -1}},//to new documents, sorted by population in reverse order
	{$group: {_id: "$_id.state",
		" Biggestcity ": {$first:" $_id.city "},//the largest population of the city
		" Biggestpop ": {$first:" Totalpop "},//the number of the largest population
		" smallestcity ": {$last: "$_id.city"},
		"Smallestpop": {$last: "Totalpop"}
	}},//re-forming a new file containing, state, maximum population and minimum population
	// The structure is basically the same
	//But we need to format the data again
	{$project:
		{_id:0, State
		: "$_id",
		biggestcity:{name: "$ Biggestcity ", Pop:" $biggestPop "},
		smallestcity:{name:" $smallestCity ", Pop:" $smallestPop "}		
		}
);


Data structure, as follows:

{"State
  ": "RI",
  "biggestcity": {
    "name": "Cranston",
    "Pop": 176404
  },
  "smallestcity ': {
    ' name ': ' Clayville ',
    ' Pop ':}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.