MongoDB and Python

 

MongoDB and Python


1. AIM

To study MongoDB, its features, architecture, and learn how to use Python (PyMongo library) to build applications that connect to MongoDB and perform CRUD operations.


2. INTRODUCTION

What is MongoDB?

MongoDB is a NoSQL document-oriented database, meaning it stores data in JSON-like documents instead of traditional rows and columns. It provides:

  • Flexible schema

  • High speed and scalability

  • Easy handling of big data

  • Horizontal scaling using sharding

MongoDB stores documents in BSON format (Binary JSON).


3. FEATURES OF MONGODB

1. Schema-less Database

Collections do not enforce any predefined structure. Each document can be different.

2. Document-Oriented

Data is stored as key–value pairs, similar to JSON.

3. High Performance

Provides fast reads/writes due to indexing, in-memory computing, and flexible storage.

4. Horizontal Scalability

Uses sharding to distribute data across multiple servers.

5. Replication

Provides failover and data redundancy using replica sets.

6. Rich Query Language

Supports filters, projections, indexing, aggregations, text search, geospatial queries, etc.


4. MONGODB ARCHITECTURE

Database → Collection → Documents

Example:

  • Database: college

  • Collection: students

  • Documents:

{ "id": 1, "name": "Alice", "age": 20, "subjects": ["Math", "Science"] }

MongoDB automatically adds an _id field as a unique primary key unless explicitly provided.


5. INSTALLATION OF MONGODB (Ubuntu/Linux)

sudo apt update sudo apt install -y mongodb sudo systemctl start mongodb sudo systemctl enable mongodb mongo --version

To check service:

systemctl status mongodb

6. MONGODB BASIC COMMANDS (SHELL)

Create or switch database:

use college

Create collection:

db.createCollection("students")

Insert document:

db.students.insertOne({id:1, name:"Alice", age:20})

Find:

db.students.find()

Update:

db.students.updateOne({id:1}, {$set:{age:21}})

Delete:

db.students.deleteOne({id:1})

7. USING PYTHON WITH MONGODB (PyMongo)

Python connects to MongoDB through the pymongo library.

Install PyMongo

pip install pymongo

8. PYTHON PROGRAM TO CONNECT TO MONGODB

from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") db = client["college"] collection = db["students"] print("Connected to MongoDB successfully!")

9. PYTHON CRUD OPERATIONS


A. INSERT DOCUMENTS

student = {"id": 1, "name": "Alice", "age": 20} collection.insert_one(student) print("Inserted:", student)

Insert Many:

collection.insert_many([ {"id": 2, "name": "Bob", "age": 22}, {"id": 3, "name": "Charlie", "age": 21} ])

B. READ DOCUMENTS

Fetch all documents:

for doc in collection.find(): print(doc)

Fetch with filter:

result = collection.find({"age": {"$gt": 20}}) for r in result: print(r)

C. UPDATE DOCUMENTS

Update one:

collection.update_one({"id": 1}, {"$set": {"age": 25}})

Update many:

collection.update_many({}, {"$inc": {"age": 1}})

D. DELETE DOCUMENTS

collection.delete_one({"id": 2})
collection.delete_many({"age": {"$gt": 23}})

10. PYTHON APPLICATION EXAMPLE (STUDENT MANAGEMENT SYSTEM)

Menu-Driven Program

from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") db = client["college"] students = db["students"] while True: print("\n1. Insert\n2. Display\n3. Search\n4. Update\n5. Delete\n6. Exit") choice = int(input("Enter choice: ")) if choice == 1: id = int(input("ID: ")) name = input("Name: ") age = int(input("Age: ")) students.insert_one({"id": id, "name": name, "age": age}) print("Inserted Successfully.") elif choice == 2: for s in students.find(): print(s) elif choice == 3: id = int(input("Enter ID: ")) print(students.find_one({"id": id})) elif choice == 4: id = int(input("Enter ID: ")) age = int(input("New Age: ")) students.update_one({"id": id}, {"$set": {"age": age}}) print("Updated Successfully.") elif choice == 5: id = int(input("Enter ID to delete: ")) students.delete_one({"id": id}) print("Deleted Successfully.") elif choice == 6: break else: print("Invalid Option")

This program shows Python + MongoDB in a real-world CRUD application.


11. ADVANCED PYTHON + MONGODB FEATURES

1. Aggregation

pipeline = [{"$group": {"_id": "$age", "count": {"$sum": 1}}}] for r in students.aggregate(pipeline): print(r)

2. Indexing

students.create_index("name")

3. Sorting

for doc in students.find().sort("age", -1): print(doc)

4. Using ObjectId

from bson.objectid import ObjectId doc = students.find_one({"_id": ObjectId("64fc3...")})

OBSERVATION

  • MongoDB supports flexible schema and dynamic documents.

  • Python PyMongo library provides easy CRUD operations.

  • Documents can contain nested structures, arrays, maps, etc.

  • Aggregation and indexing improve query efficiency.


RESULT

MongoDB concepts were studied and advanced CRUD operations were implemented using Python and PyMongo to build a student management application.

Comments

Popular posts from this blog

Database Management Systems DBMS Lab PCCSL408 Semester 4 KTU CS 2024 Scheme

DBMS Lab PCCSL408 2024 Scheme and Syllabus

Design a Database Schema for an Application Using ER Diagram from Problem Description