Chapter 0: Introduction and Aggregation Concepts
- Aggregation is a pipeline
- Pipelines are composed of one or more stages
- Stages use one or more expressions
- Expressions are functions
Aggregation
db.movies.aggregate([
{$match: {}},
{$project: {}},
{$group: {}}
])
Pipeline
const pipeline = [
{$match: {}},
{$project: {}},
{$group: {}}
]
Stage
{$match: {title: "CEO"}}
Add Expression in MongoDB(add function in aggregation)
{$add :[ "$a", "$b"]}
Introduction to the MongoDB Aggregation Framework
- Expressive filtering
- Powerful data transformation
- Statistical utilities & data analysis
- Single operation
Atlas Requirement
To connect to M121 course Atlas Cluster, using the mongo shell, you will need to use the following connection command:
mongo "mongodb://cluster0-shard-00-00-jxeqq.mongodb.net:27017,cluster0-shard-00-01-jxeqq.mongodb.net:27017,cluster0-shard-00-02-jxeqq.mongodb.net:27017/aggregations?replicaSet=Cluster0-shard-0" --authenticationDatabase admin --ssl -u m121 -p aggregations --norc
Once you’ve connected, list the existing collections of the aggregations database. Your output should be similar to this one:
Cluster0-shard-0:PRIMARY> show collections
air_airlines
air_alliances
air_routes
bronze_banking
customers
employees
exoplanets
gold_banking
icecream_data
movies
nycFacilities
silver_banking
solarSystem
stocks
system.views
The Concept of Pipelines
Pipelines are a composition of stages. Stages are configurable to produce desired transformations.
Documents flow through the stages like parts in an assembly line or water through a pipe.
The Aggregation Framework provides us many stages to filter and transform our data. Documents flow through the pipeline, passing from one stage to the next.
Aggregation Structure and Syntax
db.userColl.aggregate([{stage1}, {stage2}, ..., {stageN}], {options})
// simple first example
db.solarSystem.aggregate([{
"$match": {
"atmosphericComposition": { "$in": [/O2/] },
"meanTemperature": { $gte: -40, "$lte": 40 }
}
}, {
"$project": {
"_id": 0,
"name": 1,
"hasMoons": { "$gt": ["$numberOfMoons", 0] }
}
}], { "allowDiskUse": true});
Aggregation Pipeline Quick Reference
Some expressions can only be used in certain stages.