[MongoDB] MongoDB aggregation framework (I): mongodb aggregation framework
Question:
There are three days to end on March 13, 2014. The plan for this month has been completed in addition to the plan for summarizing Mongodb. Recently, due to laziness, mongodb research has been suspended for a long time. In the last three days, we will summarize and sort out mongodb research;
I. Basic Concepts
For an aggregate framework, I found an introduction to it in the official documentation (http://docs.mongodb.org/manual/core/aggregation-introduction. The general meaning of translation is as follows:
Aggregation is an operation that processes data records and returns computation results. Mongodb provides a powerful set of aggregate operations for checking and Calculating data sets. Running data aggregation in the mongod instance simplifies application code and limits resource requirements. Like querying, the aggregation operation in mongodb uses the set of documents as input parameters, returns results in the form of one or more documents.
Using the aggregation framework in mongodb, you can transform and combine documents in the set. You can create a pipeline with multiple builds to process a series of documents. These builds include filtering, projection, grouping, sorting, limiting, and skipping ).
The following is an instance diagram in the official document:
Ii. Basic Operators
For example, there is a collection of magazine articles. You may want to find the author who has published the most articles. If each article is saved as a document of MongoDB, follow these steps to create an MPS queue.
1. Project the authors in each document
2. Sort the authors by name and count the number of times each name appears.
3. Sort the authors by name in descending order
4. Limit the number of returned results to the first five
For operating symbol instances:
1. {'$ project': {'audio': 1} in this way, 'autor' can be projected from each document. After the execution result, this document will have {'id ': id, 'author': author}
2. {'$ group': {'id: ''' $ author', 'Count': {'$ Sum': 1 }}} will sort the authors by name, each time an author name appears, the count of each author is added.
After this step is performed, each document in the result set has the following structure: {"_ id": "authorName", "count": articleCount}
3. {"$ sort": {"count":-1} this operation will sort the documents in the result set in descending order based on the "count" Field
4. {"$ limit": 5} The result is displayed as the first five documents of the current result.
Other operating symbols: http://docs.mongodb.org/manual/reference/operator/aggregation-pipeline