Python MongoDB

MongoDB is a NoSQL database that stores data in flexible JSON-like documents instead of tables. It’s widely used for modern apps because it handles large amounts of data easily and doesn’t require a fixed schema. Python connects to MongoDB using a library called PyMongo.

Example: Think of MongoDB as a digital cupboard where each file (document) can look different but still be stored together.
To use MongoDB with Python, you need two things:
  • Install MongoDB server on your computer.
  • Install PyMongo library using pip install pymongo.
pip install pymongo
You connect to MongoDB using a MongoClient object. If MongoDB is running locally, the default port is 27017. You can also connect to remote servers or cloud services like MongoDB Atlas by changing the connection string.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
A database in MongoDB is like a folder that holds collections. You don’t need to create it manually; MongoDB automatically creates it when you first insert data. This makes it flexible and beginner-friendly.
import pymongo

# Connect to the default port on your local computer
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a database named "school"
mydb = myclient["school"]
Collections are like tables in SQL but more flexible. They hold multiple documents (records). You can create a collection by simply referencing it, and MongoDB will generate it when you insert data.
import pymongo

# Connect to the default port on your local computer
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a database named "school"
mydb = myclient["school"]

# Creating a collection called "mycol"
mycol = mydb["students"]
You can insert one document or multiple documents. Documents are written in dictionary format in Python.
import pymongo

# Connect to the default port on your local computer
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a database named "school"
mydb = myclient["school"]

# Creating a collection called "mycol"
mycol = mydb["students"]

# Inserting documents into the "students" collection
mycol.insert_one({"name": "Amit", "age": 20})
mycol.insert_many([{"name": "Sara", "age": 22}, {"name": "John", "age": 19}])
To read data, use find_one() for a single document or find() for multiple documents. You can also apply filters to narrow down results.
import pymongo

# Connect to the default port on your local computer
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a database named "school"
mydb = myclient["school"]

# Creating a collection called "mycol"
mycol = mydb["students"]

# This finds the first document in the collection
result = mycol.find_one()
print(result) # Output: The first document in the "students" collection
You can change values in documents using update_one() or update_many(). The $set operator is used to update specific fields.
import pymongo

# Connect to the default port on your local computer
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a database named "school"
mydb = myclient["school"]

# Creating a collection called "mycol"
mycol = mydb["students"]

# updating a single document
mycol.update_one({"name": "Amit"}, {"$set": {"age": 21}})
You can remove documents using delete_one() or delete_many().
import pymongo

# Connect to the default port on your local computer
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a database named "school"
mydb = myclient["school"]

# Creating a collection called "mycol"
mycol = mydb["students"]

# deleting a single document where the name is "John"
mycol.delete_one({"name": "John"})
Dropping means removing the entire collection permanently.
import pymongo

# Connect to the default port on your local computer
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a database named "school"
mydb = myclient["school"]

# Creating a collection called "mycol"
mycol = mydb["students"]

# dropping the collection
mycol.drop()
Use sort() to arrange results ascending (1) or descending (-1).
import pymongo

# Connect to the default port on your local computer
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a database named "school"
mydb = myclient["school"]

# Creating a collection called "mycol"
mycol = mydb["students"]

# sorting the documents in descending order based on the "age" field
for s in mycol.find().sort("age", -1):
  print(s)
Use limit() to restrict the number of results.
import pymongo

# Connect to the default port on your local computer
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a database named "school"
mydb = myclient["school"]

# Creating a collection called "mycol"
mycol = mydb["students"]

# limiting the results to 2 documents
for s in mycol.find().limit(2):
  print(s)
Indexes make searching faster, just like an index in a book. Without indexes, MongoDB scans every document, which is slow for large collections.
import pymongo

# Connect to the default port on your local computer
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a database named "school"
mydb = myclient["school"]

# Creating a collection called "mycol"
mycol = mydb["students"]

# indexing the "name" field
mycol.create_index("name")
Aggregation is used for calculations like sum, average, or grouping. It’s similar to SQL’s GROUP BY.
import pymongo

# Connect to the default port on your local computer
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a database named "school"
mydb = myclient["school"]

# Creating a collection called "mycol"
mycol = mydb["students"]

# aggregation pipeline to calculate the average age of students
pipeline = [{"$group": {"_id": None, "avgAge": {"$avg": "$age"}}}]
print(list(mycol.aggregate(pipeline)))

Leave a Comment

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