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.
Install PyMongo library using pip install pymongo.
pip install pymongo
Connecting to MongoDB Server
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.
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.
importpymongo
# Connect to the default port on your local computer myclient=pymongo.MongoClient("mongodb://localhost:27017/")
# Creating a database named "school" mydb=myclient["school"]
Collection
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.
importpymongo
# 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"]
Insert Data
You can insert one document or multiple documents. Documents are written in dictionary format in Python.
importpymongo
# 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}])
Find Data
To read data, use find_one() for a single document or find() for multiple documents. You can also apply filters to narrow down results.
importpymongo
# 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
Update Data
You can change values in documents using update_one() or update_many(). The $set operator is used to update specific fields.
importpymongo
# 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}})
Delete Data
You can remove documents using delete_one() or delete_many().
importpymongo
# 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"})
Drop Collection
Dropping means removing the entire collection permanently.
importpymongo
# 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()
Order By (Sorting)
Use sort() to arrange results ascending (1) or descending (-1).
importpymongo
# 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 forsinmycol.find().sort("age", -1): print(s)
Limit
Use limit() to restrict the number of results.
importpymongo
# 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 forsinmycol.find().limit(2): print(s)
Indexes
Indexes make searching faster, just like an index in a book. Without indexes, MongoDB scans every document, which is slow for large collections.
importpymongo
# 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
Aggregation is used for calculations like sum, average, or grouping. It’s similar to SQL’s GROUP BY.
importpymongo
# 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)))