الجم هــوريـة الجزائريــة الديمقراط ي ــة الشعب ي ــة
ⵜⴰⴳⴷⵓⴷⴰ ⵜⴰⴷⵣⴰⵢⵔⵉⵜ ⵜⴰⵎⴰⴳⴷⴰⵢⵜ ⵜⴰⵖⴻⵔⴼⴰⵏⵜ
People's Democratic Republic of Algeria
العلم
ي وزارة التعليم العالي والبحث
ⴰⵖⵍⵉⴼ ⵏ ⵓ ⵙⴻⵍⵎⴻⴷ ⵓⵏⵏⵉⴳ ⴷ ⵓⵏⴰⴷⵉ ⵓⵙⵙⵏⴰⵏ
Ministry of Higher Education and Scientific Research
األول لطلبة الدكتوراه الطور الثالث
ي اللجنة الوطنية ر
لإلشاف ومتابعة تنفيذ برنامج التكوين
National Steering and Monitoring Commission for the Implementation of the Early-stage Training Program for
Third-Stage Doctoral Students
البمجةي
اللجنة الوطنية البيداغوجية لمادة أساسيات وتقنيات ر
National Pedagogical Committee for Programming Fundamentals and Techniques
EARLY-STAGE TRAINING OF DOCTORAL STUDENTS
SUBJECT: PROGRAMMING FUNDAMENTALS & TECHNIQUES
PART III. FILE AND DATABASE HANDLING
PART III.2 DATABASE HANDLING IN PYTHON
PART III.2.2 NOSQL DATABASES
Academic Year Pr. Nait Bahloul Safia — [Link]@[Link]
2025/2026 Computer Science Department, Oran 1 University Ahmed Benbella, Algeria.
Course Outline
1 NoSQL Databases
2 Object Relational Mapping (ORMs)
3 Store and Retreive Data with REST APIs
Pr. Nait Bahloul Safia NoSQL Databases 1 / 26
What is a NoSQL Database?
Definition
A NoSQL database stores data without fixed tables, unlike SQL databases.
It’s like a flexible notebook for information.
Key Features
Flexible Schema: Data structure can change anytime, unlike fixed
tables in SQL.
Allows adding new fields, like grades or courses, without redefining the
database.
Use case: Storing varied student data in a university system.
Document-Oriented Storage: Data is stored as JSON-like
documents, not tables.
Documents group related data, like a student’s name, major, and
grades.
Simplifies storing complex data without multiple tables.
Pr. Nait Bahloul Safia NoSQL Databases 2 / 26
What is a NoSQL Database?
BASE Compliance: Ensures performance for large-scale apps
through:
Basically Available – Data is accessible even during failures.
Soft State – Data may change without immediate consistency.
Eventual Consistency – Updates spread across servers over time.
Varied Data Models: Supports multiple formats beyond documents.
Examples: Key-value, column-family, graph databases.
Example use case: Storing student connections in a graph for social
analysis.
Horizontal Scalability: Grows by adding servers, not bigger
machines.
Handles large datasets.
Cost-effective for big apps compared to SQL’s vertical scaling.
Use case
Perfect for apps with rapidly changing data.
Pr. Nait Bahloul Safia NoSQL Databases 3 / 26
2. Examples of NoSQL Databases
Document-oriented: MongoDB, CouchDB
Key-value stores: Redis, DynamoDB
Column-family: Cassandra, HBase
Graph databases: Neo4j
Pr. Nait Bahloul Safia NoSQL Databases 4 / 26
Introduction to MongoDB
Definition
MongoDB is a popular NoSQL database that stores data as JSON-like
documents.
Key Features
Document-oriented: Data stored in flexible “documents.”
Scalable: Handles large datasets for big apps.
Pr. Nait Bahloul Safia NoSQL Databases 5 / 26
MongoDB Document Example
Definition
A collection in MongoDB is like a Table in SQL, a collection can hold
multiple Documents. A document is like a row in SQL but can have
different fields.
Example: Student Document
{
student_id: 1,
name: "Ahmed",
major: "Computer Science"
}
Pr. Nait Bahloul Safia NoSQL Databases 6 / 26
MongoDB Operations Overview
Basic Functions
MongoDB operations manage data in collections, MongoDB can perform
the same operations as in SQL.
Create: Add new documents, e.g., inserting a new student.
Read: Retrieve documents, e.g., finding students by major.
Update: Modify existing documents, e.g., changing a student’s email
address.
Delete: Remove documents, e.g., deleting a student record.
Pr. Nait Bahloul Safia NoSQL Databases 7 / 26
MongoDB Operations Overview
SQL Equivalents
Operation SQL Equivalent MongoDB Operation
Create INSERT INTO insert many, insert one
Read SELECT find, find one
Update UPDATE update many, update one
Delete DELETE delete many, delete one
Note
These operations can be performed:
Directly in the mongo shell using MongoDB commands.
Through a programming language like Python.
We will be using Python with the pymongo library for this course.
Pr. Nait Bahloul Safia NoSQL Databases 8 / 26
Connecting Python to MongoDB
Definition
We will use Python with pymongo to connect to MongoDB and manage
data.
Before we can perform the operations, we need first to connect to the
database, then select our database name (e.g university) and choose a
collection (e.g students).
Example: Connecting to MongoDB
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['university']
collection = db['students']
Use Case
Build a student management system to store and retrieve records.
Pr. Nait Bahloul Safia NoSQL Databases 9 / 26
Inserting Data in MongoDB
Definition
Add new data (documents) to a MongoDB collection, like adding a
student.
Example: Insert a Student
collection.insert_one({
"student_id": 1,
"name": "Ahmed",
"major": "Computer Science"
})
SQL Equivalent
INSERT INTO student (student_id, name, major)
VALUES (1, 'Ahmed', 'Computer Science');
Pr. Nait Bahloul Safia NoSQL Databases 10 / 26
Finding Data in MongoDB
Definition
Search for documents in a collection, like finding students by major.
Example: Find Students
students = [Link]({"major": "Computer Science"})
for student in students:
print(student)
SQL Equivalent
SELECT * FROM student WHERE major = 'Computer Science';
Pr. Nait Bahloul Safia NoSQL Databases 11 / 26
Updating Data in MongoDB
Definition
Change existing documents, like updating a student’s major.
Example: Update a Student
collection.update_one(
{"name": "Ahmed"},
{"$set": {"major": "Data Science"}}
)
SQL Equivalent
UPDATE student
SET major = 'Data Science'
WHERE name = 'Ahmed';
Pr. Nait Bahloul Safia NoSQL Databases 12 / 26
Deleting Data in MongoDB
Definition
Remove documents from a collection, like deleting a student.
Example: Delete a Student
collection.delete_one({"name": "Ahmed"})
SQL Equivalent
DELETE FROM student WHERE name = 'Ahmed';
Pr. Nait Bahloul Safia NoSQL Databases 13 / 26
Error Handling in MongoDB
Definition
Catch mistakes, like connection issues or duplicate data, to keep your app
running.
Common Errors
Can’t connect to MongoDB server.
Adding a student with the same ID twice.
Why Handle Errors?
Prevents crashes and shows helpful messages, like “Student already exists.”
Pr. Nait Bahloul Safia NoSQL Databases 14 / 26
Error Handling Example
Definition
Use try and except in Python to handle MongoDB errors.
Example: Catching Duplicate ID
from [Link] import DuplicateKeyError
try:
collection.create_index("student_id", unique=True)
collection.insert_one({"student_id": 1, "name": "Ahmed"})
except DuplicateKeyError:
print("Error: Student ID already exists!")
Best practices: Always use error handling when doing DB queries.
Pr. Nait Bahloul Safia NoSQL Databases 15 / 26
Indexing in MongoDB
Definition
Indexes make searches faster, but only when you query on an indexed field.
Example: Indexing Student ID
collection.create_index("student_id")
Benefits
Faster queries for large datasets.
Enforces unique data, like student IDs.
Pr. Nait Bahloul Safia NoSQL Databases 16 / 26
SQL vs. NoSQL: When to Choose NoSQL
Flexible Data Needs: NoSQL allows changing data structure
without redefining tables.
SQL: Fixed schema requires predefined columns.
NoSQL: Add fields like student hobbies or courses anytime.
Use case: Managing varied student profiles in a university app.
Complex or Nested Data: NoSQL stores data in documents, ideal
for hierarchical information.
SQL: Uses multiple tables with joins for related data.
NoSQL: Stores student details (e.g., grades, address) in one document.
Use case: Tracking student grades and extracurriculars together.
Large-Scale Data: NoSQL scales across multiple servers for big
datasets.
SQL: Scales by upgrading hardware, which is costlier.
NoSQL: Handles thousands of student records efficiently.
Use case: Managing data for a large university system.
Pr. Nait Bahloul Safia NoSQL Databases 17 / 26
SQL vs. NoSQL: When to Choose NoSQL
Rapid Development: NoSQL’s flexibility speeds up app creation.
SQL: Schema changes slow down development.
NoSQL: Quick to add new features, like student feedback forms.
Use case: Building a student portal with evolving needs.
Eventual Consistency Needs: NoSQL prioritizes availability over
immediate consistency.
SQL: Ensures strict consistency with ACID transactions.
NoSQL: Allows updates to sync later for better performance.
Use case: Real-time student app with frequent updates.
Pr. Nait Bahloul Safia NoSQL Databases 18 / 26
What is an ORM?
Definition
Object-Relational Mapper: A tool that connects Python objects to SQL
database tables.
Maps classes to tables and objects to rows.
It allows developers to work on Databases using Classes and Objects
in OOP languages.
Pr. Nait Bahloul Safia NoSQL Databases 19 / 26
Features of an ORM
Simplifies Database Work: Replaces raw SQL with Python code.
Write Python classes instead of CREATE TABLE queries.
Call class methods instead of writing SELECT or INSERT queries.
Supports SQL and NoSQL Databases: Works with databases like
MySQL or PostgreSQL, but also with MongoDB.
Translates Python operations to SQL commands automatically.
Some ORMs allow developers to switch from SQL to NoSQL databases
without rewriting all their queries.
Popular ORM Example: SQLAlchemy is widely used in Python.
Flexible and works with or without frameworks.
Simplifies tasks like adding or querying students.
Pr. Nait Bahloul Safia NoSQL Databases 20 / 26
When Do We Need ORMs?
Complex Applications: ORMs simplify managing multiple tables
and relationships.
SQL: Requires writing many queries for students, lecturers, and courses.
ORM: Uses Python classes to handle relationships easily.
Use case: Tracking student enrollments in courses.
Faster Development: ORMs reduce repetitive SQL coding.
Write less code to add, update, or query data.
Example: Quickly add a new student to the database.
Safer Code: ORMs prevent errors like SQL injection.
Automatically handle query safety.
Use case: Securely store and retrieve student emails and passwords for
login.
Easy Database Switching: Change databases without rewriting
code.
Switch from MySQL to PostgreSQL with minimal changes.
Use case: Testing a student app on different databases.
Pr. Nait Bahloul Safia NoSQL Databases 21 / 26
ORM Example
The example below defines a student Table as a Python class using
SQLAlchemy.
Example: Student Class
from sqlalchemy import Column, Integer, String
from [Link] import declarative_base
Base = declarative_base()
class Student(Base):
__tablename__ = 'students'
student_id = Column(Integer, primary_key=True)
name = Column(String)
major = Column(String)
Pr. Nait Bahloul Safia NoSQL Databases 22 / 26
Using an ORM class
Use the student class to add and query data without writing SQL.
Example: Adding and Querying a Student
from [Link] import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
# Add a student
new_student = Student(student_id=1, name="Ahmed", major="Computer Science")
[Link](new_student)
[Link]()
# Query a student
student = [Link](Student).filter_by(name="Ahmed").first()
print([Link])
Pr. Nait Bahloul Safia NoSQL Databases 23 / 26
Use Cases for REST APIs
Safe Database Access: REST APIs allow controlled access to the
database over the web.
Expose only specific data, like student names, not the entire database.
Use case: Displaying student records on a website, with a separate
frontend and backend.
Web Integration: Connects the database to web or mobile apps.
Users can view or update data via a browser or app.
Scalable Interaction: Handles multiple users accessing data at once.
Supports many requests, like students registering for courses.
Standardized Communication: Uses HTTP methods (GET, POST)
for consistency.
Easy for developers to integrate with other systems.
Helps write reusable endpoints for App developers.
Pr. Nait Bahloul Safia NoSQL Databases 24 / 26
What is Flask?
Definition : Flask is a Web Framework: a tool to build web applications.
It allows to create web pages or APIs to interact with databases.
Key Features
Lightweight and Flexible: Easy to learn and customize.
Minimal setup for small projects like a student app.
Works well with MongoDB’s data format.
REST API Support: Creates endpoints for database operations.
Example: An endpoint to list all students.
Example: An endpoint to register a new student.
Installation: Simple to set up with Python.
Install using pip install flask.
Quick start for beginners
[Link]
Pr. Nait Bahloul Safia NoSQL Databases 25 / 26
REST API Use Case with Flask
Create a REST API with Flask to display MongoDB student data on the
web.
Example: List Students
from flask import Flask
from pymongo import MongoClient
app = Flask(__name__)
client = MongoClient('mongodb://localhost:27017/')
db = client['university']
students = db['students']
@[Link]('/students')
def get_students():
student_list = list([Link]({}, {'_id': 0}))
return student_list
Usage
We can fetch students by sending a GET HTTP request to the /students
URL.
Pr. Nait Bahloul Safia NoSQL Databases 26 / 26