Python MongoDB

Module 2: MongoDB Basics – Complete Chapter

Welcome to Module 2. In this chapter, we will explore MongoDB, a powerful NoSQL database.
You will learn the differences between SQL and NoSQL, how to install MongoDB locally or use Atlas, and perform CRUD operations.
We will also cover data types, query operators, indexing, and best practices for efficient database design.

✅ NoSQL vs SQL

Relational databases (SQL) use tables, rows, and fixed schemas, while NoSQL databases (like MongoDB) use flexible, document-based storage.

  • SQL: Good for structured data, complex transactions, joins.
  • NoSQL: Good for unstructured/semi-structured data, scalability, fast reads/writes.
  • MongoDB stores data in JSON-like documents inside collections, allowing dynamic fields per document.

🔹 When to use MongoDB

  • Applications with rapidly changing data structures.
  • High scalability and distributed systems.
  • Real-time analytics, caching, or logging data.

✅ Installing MongoDB

🔹 Local Installation

  • Windows: Download MSI installer from MongoDB Community Edition. Run installer and configure MongoDB as a service.
  • Linux: Use apt or yum depending on your distro:
# Ubuntu example
sudo apt update
sudo apt install -y mongodb
  • macOS: Use Homebrew
brew tap mongodb/brew
brew install mongodb-community@7.0

🔹 MongoDB Atlas (Cloud)

  • Sign up at MongoDB Atlas.
  • Create a free cluster and database user.
  • Whitelist your IP address and get the connection string for remote access.

✅ Databases, Collections & Documents

MongoDB stores data as documents (JSON-like), inside collections, which reside in a database.

# Connect to local MongoDB
mongo

# Show databases
show dbs

# Create/use database
use mydb

# Create collection & insert document
db.users.insertOne({name: "Ali", age: 25, role: "student"})

# Show collections
show collections

# Find documents
db.users.find()

🔹 Notes

  • A database contains multiple collections.
  • Collections contain multiple documents (similar to rows in SQL).
  • Documents are JSON-like objects with dynamic fields.

✅ CRUD Operations in Mongo Shell

🔹 Create

db.users.insertOne({name:"Ali", age:25})
db.users.insertMany([{name:"Sara"}, {name:"John"}])

🔹 Read

db.users.find()
db.users.find({age: {$gt: 20}})
db.users.findOne({name:"Ali"})

🔹 Update

db.users.updateOne({name:"Ali"}, {$set:{age:26}})
db.users.updateMany({}, {$set:{status:"active"}})

🔹 Delete

db.users.deleteOne({name:"John"})
db.users.deleteMany({age:{$lt:18}})

✅ MongoDB Data Types

  • String – text
  • NumberInt / NumberLong / Double – integers & floats
  • Boolean – true / false
  • Date – ISODate
  • Array – list of values
  • ObjectId – unique ID for documents
  • Embedded Documents – nested JSON

✅ Query Operators

# $gt, $lt, $in, $or, $and
db.users.find({age: {$gt:20}})
db.users.find({$or:[{role:"student"},{age:{$lt:30}}]})
db.users.find({age: {$in:[25,30,35]}})

✅ Indexing Basics

Indexes improve query performance by creating a reference to documents.

# Create index on name
db.users.createIndex({name:1})

# Drop index
db.users.dropIndex("name_1")
  • Use indexes on fields frequently used in queries.
  • Over-indexing increases write cost, so index wisely.

✅ Exercises

  • Create a database school with collections students and teachers.
  • Insert 5 student documents with name, age, and class.
  • Find all students older than 15.
  • Update a student’s class using updateOne.
  • Create an index on the name field and test query speed.

Congratulations! You have completed Module 2: MongoDB Basics. You now understand the MongoDB ecosystem, basic CRUD operations, data types, query operators, and indexing. You are ready to integrate Python with MongoDB in Module 3.

Leave a Reply

Your email address will not be published. Required fields are marked *