In this section, we will explore how to use MongoDB with Python. Python is a versatile and widely-used programming language, and integrating it with MongoDB allows developers to build powerful and scalable applications. We will cover the following topics:
- Setting Up the Environment
- Connecting to MongoDB
- CRUD Operations with PyMongo
- Using MongoEngine for Object-Document Mapping (ODM)
- Practical Exercises
- Setting Up the Environment
Before we start working with MongoDB in Python, we need to set up our environment.
Installing MongoDB
If you haven't installed MongoDB yet, refer to the "Installing MongoDB" section in Module 1.
Installing PyMongo
PyMongo is the official MongoDB driver for Python. You can install it using pip:
Installing MongoEngine (Optional)
MongoEngine is an Object-Document Mapper (ODM) for MongoDB, similar to an ORM for SQL databases. You can install it using pip:
- Connecting to MongoDB
Let's start by connecting to a MongoDB instance using PyMongo.
Example Code
from pymongo import MongoClient
# Replace the URI string with your MongoDB deployment's connection string.
client = MongoClient("mongodb://localhost:27017/")
# Access the 'test' database
db = client.test
print("Connected to MongoDB!")Explanation
- MongoClient: This class is used to connect to a MongoDB instance. The connection string specifies the address of the MongoDB server.
- db: This variable represents the 'test' database. If the database does not exist, MongoDB will create it when you first store data in it.
- CRUD Operations with PyMongo
Creating Documents
To insert documents into a collection, use the insert_one or insert_many methods.
Example Code
# Access the 'users' collection
users_collection = db.users
# Insert a single document
user = {"name": "Alice", "age": 25, "email": "[email protected]"}
result = users_collection.insert_one(user)
print(f"Inserted document with _id: {result.inserted_id}")
# Insert multiple documents
users = [
{"name": "Bob", "age": 30, "email": "[email protected]"},
{"name": "Charlie", "age": 35, "email": "[email protected]"}
]
result = users_collection.insert_many(users)
print(f"Inserted documents with _ids: {result.inserted_ids}")Reading Documents
To read documents from a collection, use the find_one or find methods.
Example Code
# Find a single document
user = users_collection.find_one({"name": "Alice"})
print(user)
# Find multiple documents
for user in users_collection.find({"age": {"$gt": 25}}):
print(user)Updating Documents
To update documents, use the update_one or update_many methods.
Example Code
# Update a single document
result = users_collection.update_one({"name": "Alice"}, {"$set": {"age": 26}})
print(f"Matched {result.matched_count} document(s) and modified {result.modified_count} document(s)")
# Update multiple documents
result = users_collection.update_many({"age": {"$gt": 25}}, {"$set": {"status": "active"}})
print(f"Matched {result.matched_count} document(s) and modified {result.modified_count} document(s)")Deleting Documents
To delete documents, use the delete_one or delete_many methods.
Example Code
# Delete a single document
result = users_collection.delete_one({"name": "Alice"})
print(f"Deleted {result.deleted_count} document(s)")
# Delete multiple documents
result = users_collection.delete_many({"age": {"$lt": 30}})
print(f"Deleted {result.deleted_count} document(s)")
- Using MongoEngine for Object-Document Mapping (ODM)
MongoEngine provides a higher-level abstraction for working with MongoDB in Python.
Example Code
from mongoengine import connect, Document, StringField, IntField, EmailField
# Connect to MongoDB
connect('test')
# Define a User document
class User(Document):
name = StringField(required=True)
age = IntField(required=True)
email = EmailField(required=True)
# Create a new user
user = User(name="Alice", age=25, email="[email protected]")
user.save()
# Query users
for user in User.objects(age__gt=25):
print(user.name, user.age, user.email)Explanation
- connect: Connects to the specified MongoDB database.
- Document: Base class for defining documents.
- StringField, IntField, EmailField: Field types for the document schema.
- save: Saves the document to the database.
- objects: Query interface for retrieving documents.
- Practical Exercises
Exercise 1: Insert and Query Data
- Insert three new users into the
userscollection. - Query and print all users who are older than 28.
Solution
# Insert new users
new_users = [
{"name": "David", "age": 28, "email": "[email protected]"},
{"name": "Eve", "age": 32, "email": "[email protected]"},
{"name": "Frank", "age": 29, "email": "[email protected]"}
]
users_collection.insert_many(new_users)
# Query and print users older than 28
for user in users_collection.find({"age": {"$gt": 28}}):
print(user)Exercise 2: Update and Delete Data
- Update the email of the user named "Bob" to "[email protected]".
- Delete all users who are younger than 30.
Solution
# Update Bob's email
users_collection.update_one({"name": "Bob"}, {"$set": {"email": "[email protected]"}})
# Delete users younger than 30
users_collection.delete_many({"age": {"$lt": 30}})Conclusion
In this section, we learned how to integrate MongoDB with Python using PyMongo and MongoEngine. We covered the basics of connecting to MongoDB, performing CRUD operations, and using an ODM for higher-level abstractions. These skills are essential for building robust and scalable applications with MongoDB and Python. In the next module, we will explore real-world applications of MongoDB.
