MongoDB is a popular NoSQL database that pairs excellently with Python. This guide will walk you through the basics of using MongoDB in your Python applications.
To begin working with MongoDB in Python, you'll need to install the PyMongo driver. Use pip to install it:
pip install pymongo
Establishing a connection to MongoDB is straightforward:
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
# Access a database
db = client['mydatabase']
# Access a collection
collection = db['mycollection']
To insert a document into a collection:
# Insert one document
result = collection.insert_one({"name": "John", "age": 30})
print(f"Inserted ID: {result.inserted_id}")
# Insert multiple documents
documents = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 35}
]
result = collection.insert_many(documents)
print(f"Inserted IDs: {result.inserted_ids}")
Retrieving documents from MongoDB is simple:
# Find one document
doc = collection.find_one({"name": "John"})
print(doc)
# Find multiple documents
for doc in collection.find({"age": {"$gt": 25}}):
print(doc)
Updating documents can be done using various methods:
# Update one document
result = collection.update_one(
{"name": "John"},
{"$set": {"age": 31}}
)
print(f"Modified count: {result.modified_count}")
# Update multiple documents
result = collection.update_many(
{"age": {"$lt": 30}},
{"$inc": {"age": 1}}
)
print(f"Modified count: {result.modified_count}")
Removing documents from a collection is straightforward:
# Delete one document
result = collection.delete_one({"name": "John"})
print(f"Deleted count: {result.deleted_count}")
# Delete multiple documents
result = collection.delete_many({"age": {"$gt": 35}})
print(f"Deleted count: {result.deleted_count}")
As you become more comfortable with Python MongoDB integration, explore these advanced concepts:
MongoDB's flexibility and Python's simplicity make for a powerful combination in building scalable applications. As you progress, you may want to explore how MongoDB integrates with other Python web frameworks or compare it with SQL databases using Python SQLite or Python MySQL Connector.
Python MongoDB integration offers a robust solution for handling unstructured data in your applications. By mastering these basics, you'll be well-equipped to build sophisticated, data-driven Python applications using MongoDB as your database backend.