Sitemap

Member-only story

Data Manipulation with MongoDB Aggregation Framework in Python

4 min readApr 3, 2024

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…

--

--

Afzal Badshah, PhD
Afzal Badshah, PhD

Written by Afzal Badshah, PhD

Dr Afzal Badshah focuses on academic skills, pedagogy (teaching skills) and life skills.

No responses yet