Data Manipulation with MongoDB Aggregation Framework in Python
MongoDB Aggregation Framework is a powerful tool that allows for data manipulation and analysis within MongoDB collections. It provides a flexible and efficient way to process and transform data, enabling users to perform complex operations such as grouping, sorting, filtering, and computing aggregate values. In this lab tutorial, we will introduce the concepts of MongoDB Aggregation Framework, provide a detailed explanation of the code, and walk through each line to understand its functionality. Visit the detailed tutorial here.
Code
import pymongo
from pymongo import MongoClient
# Connect to MongoDB
client = pymongo.MongoClient("mongodb+srv://user:pass@cluster0.ergtejf.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0")
# Switch to the desired database
db = client.afzal
collection = db.test
# Insert sample data into a collection
db.collection.insert_many([
{ 'name': 'Afzal', 'age': 25, 'city': 'Islamabad' },
{ 'name': 'Jalal', 'age': 28, 'city': 'Mianwali' }
{ 'name': 'Yousaf', 'age': 30, 'city': 'Quetta' },
{ 'name': 'Ibrahim', 'age': 35, 'city': 'Karachi' },
])
print("Total documents in collection:", db.collection.count_documents({}))
# Calculate average age
pipeline_avg_age = [{ '$group': { '_id': None, 'avgAge': { '$avg': '$age' } } }]
avg_age_result = list(db.collection.aggregate(pipeline_avg_age))
print("Average age:", avg_age_result[0]['avgAge'])
# Group by city and count
pipeline_city_count = [{ '$group': { '_id': '$city', 'count': { '$sum': 1 } } }]
city_count_result = list(db.collection.aggregate(pipeline_city_count))
print("City count:", city_count_result)
# Group by city and find max age
pipeline_max_age = [{ '$group': { '_id': '$city', 'maxAge': { '$max': '$age' } } }]
max_age_result = list(db.collection.aggregate(pipeline_max_age))
print("Max age by city:", max_age_result)
# Filter documents where age is greater than 25
pipeline_filtered = [{ '$match': { 'age': { '$gt': 25 } } }]
filtered_result = list(db.collection.aggregate(pipeline_filtered))
print("Filtered documents:", filtered_result)
# Sort documents by age in descending order
pipeline_sorted = [{ '$sort': { 'age': -1 } }]
sorted_result = list(db.collection.aggregate(pipeline_sorted))
print("Sorted documents:", sorted_result)
Connection and Database Selection
Contents
- We import the necessary libraries
pymongo
andMongoClient
. - We establish a connection to the MongoDB server using the connection string (replace with your actual connection details).
- We specify the desired database (
afzal
) and collection (test
) within the connected client.
import pymongo
from pymongo import MongoClient
# Connect to MongoDB (replace with your connection details)
client = pymongo.MongoClient("mongodb+srv://user:pass@cluster0.ergtejf.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0")
# Switch to the desired database and collection (replace with your database and collection names)
db = client.afzal
collection = db.test
Sample Data and Counting Documents
- We insert sample data containing documents with names, ages, and cities.
- We use
db.collection.insert_many
to insert multiple documents at once. - We then count the total number of documents in the collection using
db.collection.count_documents({})
. The empty dictionary{}
specifies matching all documents.
# Insert sample data into a collection
db.collection.insert_many([
{ 'name': 'Afzal', 'age': 25, 'city': 'Islamabad' },
{ 'name': 'Jalal', 'age': 28, 'city': 'Mianwali' }
{ 'name': 'Yousaf', 'age': 30, 'city': 'Quetta' },
{ 'name': 'Ibrahim', 'age': 35, 'city': 'Karachi' },
])
print("Total documents in collection:", db.collection.count_documents({}))
Calculating Average Age
- We define an aggregation pipeline named
pipeline_avg_age
. - The pipeline consists of a single stage using the
$group
operator._id: None
discards the original document’s_id
field in the output.$avg
: This operator calculates the average value of theage
field and stores it in theavgAge
field of the output document.
- We use
db.collection.aggregate(pipeline_avg_age)
to execute the pipeline and retrieve the results. - We convert the results to a list using
list
and access the first element (since there’s only one document in the output) to get the average age stored in theavgAge
field.
# Calculate average age
pipeline_avg_age = [{ '$group': { '_id': None, 'avgAge': { '$avg': '$age' } } }]
avg_age_result = list(db.collection.aggregate(pipeline_avg_age))
print("Average age:", avg_age_result[0]['avgAge'])
Grouping by City and Counting Documents
- The pipeline groups documents by their
city
using$group
. _id: '$city'
sets the group identifier to thecity
field value.$sum: 1
increments a counter for each document in the group, resulting in a count of documents for each city.- We process and print the results similar to the previous step.
# Group by city and find max age
pipeline_max_age = [{ '$group': { '_id': '$city', 'maxAge': { '$max': '$age' } } }]
max_age_result = list(db.collection.aggregate(pipeline_max_age))
print("Max age by city:", max_age_result)
# Group by city and count
pipeline_city_count = [{ '$group': { '_id': '$city', 'count': { '$sum': 1 } } }]
city_count_result = list(db.collection.aggregate(pipeline_city_count))
print("City count:", city_count_result)
Grouping by City and Finding Maximum Age
- The pipeline groups documents by city using
$group
with_id: '$city'
. $max: '$age'
calculates the maximum value of theage
field within each group, storing it in themaxAge
field of the output document.- We process and print the results as in previous steps.
pipeline_max_age = [{ '$group': { '_id': '$city', 'maxAge': { '$max': '$age' } } }]
max_age_result = list(db.collection.aggregate(pipeline_max_age))
print("Max age by city:", max_age_result)
Filtering Documents
- We define a pipeline with a single stage using the
$match
operator. $match
filters documents based on a criteria. Here, it selects documents where theage
is greater than ($gt
) 25.- We process and print the results, showcasing the filtered documents.
# Filter documents where age is greater than 25
pipeline_filtered = [{ '$match': { 'age': { '$gt': 25 } } }]
filtered_result = list(db.collection.aggregate(pipeline_filtered))
print("Filtered documents:", filtered_result)
Sorting Documents
- The pipeline uses the
$sort
operator to arrange documents. - Here,
age: -1
sorts documents by theage
field in descending order (highest age first). - We process and print the results, displaying the sorted documents.
# Sort documents by age in descending order
pipeline_sorted = [{ '$sort': { 'age': -1 } }]
sorted_result = list(db.collection.aggregate(pipeline_sorted))
print("Sorted documents:", sorted_result)
107 thoughts on “Data Manipulation with MongoDB Aggregation Framework in Python”
Farmacie online sicure: Farma Prodotti – farmacia online
comprare farmaci online all’estero
acquistare farmaci senza ricetta: Farma Prodotti – Farmacie on line spedizione gratuita
Farmacie online sicure
viagra generico sandoz viagra prezzo viagra originale in 24 ore contrassegno
comprare farmaci online all’estero: Cialis generico farmacia – migliori farmacie online 2024
farmaci senza ricetta elenco
Many casinos offer luxurious amenities and services.: phmacao com login – phmacao com login
Game rules can vary between casinos. http://phmacao.life/# Entertainment shows are common in casinos.
http://phmacao.life/# A variety of gaming options cater to everyone.
Slot machines feature various exciting themes.
Las experiencias son Гєnicas en cada visita.: winchile casino – winchile.pro
jugabet chile jugabet casino Los jugadores disfrutan del pГіker en lГnea.
Entertainment shows are common in casinos.: taya777 login – taya777 app
http://phmacao.life/# Live dealer games enhance the casino experience.
Many casinos provide shuttle services for guests.
Players must be at least 21 years old. https://winchile.pro/# Los casinos celebran festivales de juego anualmente.
Resorts provide both gaming and relaxation options.: taya777 app – taya777 register login
order azithromycin 250mg pill – oral bystolic 5mg buy nebivolol 20mg without prescription
Muchos casinos tienen salas de bingo.: winchile – winchile casino
http://winchile.pro/# La diversiГіn nunca se detiene en los casinos.
Slot machines attract players with big jackpots.
The casino atmosphere is thrilling and energetic. https://taya365.art/# Slot tournaments create friendly competitions among players.
jugabet chile jugabet chile Muchos casinos ofrecen restaurantes y bares.
Los jackpots progresivos atraen a los jugadores.: winchile.pro – win chile
https://phtaya.tech/# Many casinos host charity events and fundraisers.
Live music events often accompany gaming nights.
The casino atmosphere is thrilling and energetic.: phmacao – phmacao
Many casinos have beautiful ocean views. http://phtaya.tech/# Game rules can vary between casinos.
Players enjoy a variety of table games.: taya777 register login – taya777 register login
http://winchile.pro/# Los casinos organizan eventos especiales regularmente.
Players must be at least 21 years old.
Players often share tips and strategies.: phmacao com – phmacao com
taya777 login taya777 login Casino visits are a popular tourist attraction.
Many casinos have beautiful ocean views. https://jugabet.xyz/# La seguridad es prioridad en los casinos.
https://winchile.pro/# Las reservas en lГnea son fГЎciles y rГЎpidas.
Casinos often host special holiday promotions.
Many casinos offer luxurious amenities and services.: phmacao club – phmacao com
Las estrategias son clave en los juegos.: winchile casino – winchile casino
http://phmacao.life/# Loyalty programs reward regular customers generously.
Many casinos have beautiful ocean views.
п»їCasinos in the Philippines are highly popular. http://taya365.art/# The thrill of winning keeps players engaged.
The thrill of winning keeps players engaged.: phmacao – phmacao com
phtaya login phtaya casino The gaming floors are always bustling with excitement.
Players enjoy a variety of table games.: taya365.art – taya365
https://taya365.art/# Many casinos have beautiful ocean views.
Manila is home to many large casinos.
Visitors come from around the world to play. https://winchile.pro/# Las promociones atraen nuevos jugadores diariamente.
Los casinos organizan eventos especiales regularmente.: jugabet.xyz – jugabet.xyz
https://taya365.art/# High rollers receive exclusive treatment and bonuses.
The Philippines has several world-class integrated resorts.
Many casinos host charity events and fundraisers.: taya365 login – taya365
The poker community is very active here. https://jugabet.xyz/# Los jugadores pueden disfrutar desde casa.
https://taya365.art/# Visitors come from around the world to play.
Casinos offer delicious dining options on-site.
win chile winchile п»їLos casinos en Chile son muy populares.
Los jugadores pueden disfrutar desde casa.: win chile – win chile
Los casinos organizan eventos especiales regularmente.: winchile.pro – win chile
http://phmacao.life/# Most casinos offer convenient transportation options.
The Philippines has several world-class integrated resorts.
Gambling can be a social activity here. https://phmacao.life/# Loyalty programs reward regular customers generously.
Los juegos en vivo ofrecen emociГіn adicional.: winchile – winchile.pro
Las promociones atraen nuevos jugadores diariamente.: jugabet chile – jugabet casino
https://winchile.pro/# La variedad de juegos es impresionante.
Slot machines feature various exciting themes.
Players enjoy both fun and excitement in casinos. https://phtaya.tech/# Casino visits are a popular tourist attraction.
Los casinos son lugares de reuniГіn social.: winchile.pro – winchile.pro
Some casinos feature themed gaming areas.: phmacao casino – phmacao casino
https://winchile.pro/# Los casinos celebran festivales de juego anualmente.
Casinos often host special holiday promotions.
Many casinos provide shuttle services for guests.: phmacao – phmacao com login
https://jugabet.xyz/# Las aplicaciones mГіviles permiten jugar en cualquier lugar.
Casinos offer delicious dining options on-site.
Hay casinos en Santiago y ViГ±a del Mar.: win chile – winchile.pro
win chile win chile La Г©tica del juego es esencial.
order prednisolone sale – omnacortil 20mg generic order generic progesterone 200mg
https://winchile.pro/# La Г©tica del juego es esencial.
Resorts provide both gaming and relaxation options.
Loyalty programs reward regular customers generously.: taya777 app – taya777.icu
The ambiance is designed to excite players.: taya777 login – taya777
https://winchile.pro/# Las estrategias son clave en los juegos.
Cashless gaming options are becoming popular.
Slot machines feature various exciting themes.: phtaya login – phtaya
Los jugadores disfrutan del pГіker en lГnea.: jugabet.xyz – jugabet chile
https://winchile.pro/# La seguridad es prioridad en los casinos.
Visitors come from around the world to play.
winchile winchile casino Los jugadores pueden disfrutar desde casa.
Visitors come from around the world to play.: phtaya casino – phtaya.tech
The ambiance is designed to excite players.: taya777 login – taya777 login
https://taya777.icu/# The Philippines offers a rich gaming culture.
Casinos often host special holiday promotions.
High rollers receive exclusive treatment and bonuses.: taya777 login – taya777
http://jugabet.xyz/# Las experiencias son Гєnicas en cada visita.
Casino promotions draw in new players frequently.
Players can enjoy high-stakes betting options.: taya777 login – taya777 login
phtaya casino phtaya.tech Online gaming is also growing in popularity.
Casino promotions draw in new players frequently. https://taya777.icu/# Casinos often host special holiday promotions.
https://taya365.art/# High rollers receive exclusive treatment and bonuses.
Manila is home to many large casinos.
Los juegos de mesa son clГЎsicos eternos.: win chile – winchile casino
https://phmacao.life/# Entertainment shows are common in casinos.
The thrill of winning keeps players engaged.
Security measures ensure a safe environment.: phtaya login – phtaya login
taya777 login taya777 app The casino experience is memorable and unique.
Los pagos son rГЎpidos y seguros.: jugabet – jugabet chile
Players often share tips and strategies. https://phtaya.tech/# Players enjoy a variety of table games.
La seguridad es prioridad en los casinos.: win chile – winchile.pro
https://taya365.art/# The casino experience is memorable and unique.
Many casinos host charity events and fundraisers.
Manila is home to many large casinos.: phtaya casino – phtaya
Hay casinos en Santiago y ViГ±a del Mar.: winchile casino – winchile
https://jugabet.xyz/# Los jackpots progresivos atraen a los jugadores.
Entertainment shows are common in casinos.
jugabet jugabet La diversiГіn nunca se detiene en los casinos.
Los bonos de bienvenida son generosos.: winchile casino – winchile casino
http://winchile.pro/# Los torneos de poker generan gran interГ©s.
Slot machines feature various exciting themes.
Entertainment shows are common in casinos.: phmacao casino – phmacao
drug mart: cheapest prescription pharmacy – drug mart
canadian pharmacy world coupons https://familypharmacy.company/# online pharmacy delivery usa
cheapest pharmacy to fill prescriptions with insurance http://familypharmacy.company/# Online pharmacy USA
buy medicines online in india: Mega India Pharm – MegaIndiaPharm
easy canadian pharm easy canadian pharm easy canadian pharm
easy canadian pharm: easy canadian pharm – pharmacy wholesalers canada
cheapest pharmacy to fill prescriptions with insurance http://familypharmacy.company/# canadian pharmacy coupon code
xxl mexican pharm: xxl mexican pharm – mexico drug stores pharmacies
online pharmacy discount code https://familypharmacy.company/# Best online pharmacy
Mega India Pharm: online shopping pharmacy india – Mega India Pharm
canadian pharmacy world coupon http://familypharmacy.company/# Best online pharmacy
best online pharmacy india online shopping pharmacy india top online pharmacy india
mexican rx online: xxl mexican pharm – buying prescription drugs in mexico
canadian pharmacy world coupons https://megaindiapharm.com/# pharmacy website india
canada pharmacy coupon http://discountdrugmart.pro/# discount drug mart
indian pharmacy paypal: buy medicines online in india – Mega India Pharm