MongoDB Aggregation Framework (part 2)
Part II of the post MongoDB Aggregation Framework
MongoDB vs SQL
As I know that most of you come from SQL world, I am going to show the equivalence between the sql functions and the functions we will use with the aggregation framework.
|MongoDB Aggregation Operators||SQL Functions|
- $project: Reshapes each document in the stream, include, exclude or rename fields, inject computed fields, create sub-document fields, using mathematical expressions, dates, strings and/or logical (comparison, boolean, control) expressions
- $match: Filters the document stream to allow only matching documents to pass unmodified into the next pipeline stage.
- $redact: Reshapes each document in the stream by restricting the content for each document based on information stored in the documents themselves. Incorporates the functionality of $project and $match.
- $limit: Limits the number of documents passed to the next stage.
- $skip: Skips over the specified number of documents that pass into the stage and passes the remaining documents to the next stage.
- $unwind: Expand documents. Deconstructs an array field from the input documents to output a document for each element.
- $group: Summarize documents. Groups input documents by a specified identifier expression and applies the accumulator expression(s).
- $sort: Order documents by one or more fields.
- $geoNear: Returns an ordered stream of documents based on the proximity to a geospatial point.
- $out: Writes the resulting documents of the aggregation pipeline to a collection. It must be the last stage in the pipeline.
For a deeper dive into any of these expressions you can visit this url: http://docs.mongodb.org/manual/meta/aggregation-quick-reference/#expressions
Accumulators (available only for the $group stage)
Single Purpose Aggregation Operations
- Count: MongoDB can return a count of the number of documents that match a query.
- Distinct: The distinct operation takes a number of documents that match a query and returns all of the unique values for a field in the matching documents.
- Group: The group operation takes a number of documents that match a query, and then collects groups of documents based on the value of a field or fields. It returns an array of documents with computed results for each group of documents.