MongoDB

suggest change

MongoDB is a popular document-oriented NoSQL database that stores data in flexible, schema-less BSON (Binary JSON) documents. In Python, the official driver is pymongo. It provides both a synchronous API (MongoClient) and, since PyMongo 4.13, a native asynchronous API (AsyncMongoClient) for asyncio applications such as FastAPI. The older async driver motor is deprecated in favor of it.


1. Installation

Install pymongo:

pip install pymongo

2. Connecting with pymongo

Create a MongoClient instance to connect to a local instance, Docker container, or MongoDB Atlas cluster:

from pymongo import MongoClient

# Connect to MongoDB
client = MongoClient(
    "mongodb://localhost:27017/",
    maxPoolSize=50,             # Connection pool size
    serverSelectionTimeoutMS=5000 # 5-second timeout for server selection
)

# Access database and collection (created automatically on first insert)
db = client["store_database"]
products = db["products"]

3. CRUD Operations

Inserting Documents

from datetime import datetime, timezone

# Insert a single document
new_product = {
    "name": "Mechanical Keyboard",
    "price": 129.99,
    "category": "Electronics",
    "in_stock": True,
    "tags": ["mechanical", "rgb", "usb-c"],
    "created_at": datetime.now(timezone.utc)
}

result = products.insert_one(new_product)
print(f"Inserted document ID: {result.inserted_id}")

# Insert multiple documents in bulk
items = [
    {"name": "Wireless Mouse", "price": 49.99, "category": "Electronics"},
    {"name": "Desk Mat", "price": 25.00, "category": "Accessories"}
]
batch_result = products.insert_many(items)
print(f"Inserted IDs: {batch_result.inserted_ids}")

Querying Documents (find and find_one)

find() returns a cursor that lazily streams documents from the database:

from bson import ObjectId

# Find a single document
item = products.find_one({"name": "Mechanical Keyboard"})
print(f"Found: {item['name']} - ${item['price']}")

# Query with operators ($gte, $in, $regex)
query = {
    "price": {"$gte": 40.00},
    "category": "Electronics"
}

# Sort descending by price (-1) and limit to top 5
cursor = products.find(query).sort("price", -1).limit(5)

for doc in cursor:
    print(f"{doc['name']}: ${doc['price']} (ID: {doc['_id']})")

# Query by BSON ObjectId
target_id = ObjectId("657f1a2b3c4d5e6f7a8b9c0d")
doc_by_id = products.find_one({"_id": target_id})

Updating Documents

Use update operators such as $set, $inc, and $push:

# Update a single document
products.update_one(
    {"name": "Mechanical Keyboard"},
    {
        "$set": {"price": 119.99},
        "$inc": {"inventory_count": -1}
    }
)

# Update multiple documents matching criteria
result = products.update_many(
    {"category": "Accessories"},
    {"$set": {"on_sale": True}}
)
print(f"Matched: {result.matched_count}, Modified: {result.modified_count}")

Deleting Documents

# Delete a single document
products.delete_one({"name": "Desk Mat"})

# Delete all out-of-stock items
deleted = products.delete_many({"in_stock": False})
print(f"Deleted {deleted.deleted_count} out-of-stock items")

4. Aggregation Pipelines

Aggregation pipelines perform multi-stage data processing and grouping on the server:

pipeline = [
    # Stage 1: Filter to in-stock items
    {"$match": {"in_stock": True}},

    # Stage 2: Group by category and calculate statistics
    {
        "$group": {
            "_id": "$category",
            "total_items": {"$sum": 1},
            "avg_price": {"$avg": "$price"},
            "max_price": {"$max": "$price"}
        }
    },

    # Stage 3: Sort by total items descending
    {"$sort": {"total_items": -1}}
]

results = list(products.aggregate(pipeline))
for row in results:
    print(f"Category: {row['_id']} | Items: {row['total_items']} | Avg: ${row['avg_price']:.2f}")

5. Asynchronous MongoDB with AsyncMongoClient (asyncio)

In modern async frameworks like FastAPI, blocking calls in pymongo can block the event loop. Use PyMongo's AsyncMongoClient for non-blocking asynchronous operations (it replaces the deprecated Motor library):

import asyncio
from pymongo import AsyncMongoClient

async def main():
    client = AsyncMongoClient("mongodb://localhost:27017")
    db = client["async_store"]
    collection = db["logs"]

    # Async insert
    await collection.insert_one({"event": "login", "user": "alice"})

    # Async cursor iteration
    async for doc in collection.find({"event": "login"}):
        print(f"Log: {doc['user']}")

    await client.close()

asyncio.run(main())

6. Creating Indexes for Performance

Queries without indexes result in slow collection scans. Create indexes on frequently queried fields:

from pymongo import ASCENDING, DESCENDING

# Create a single field index
products.create_index([("name", ASCENDING)], unique=True)

# Create a compound index
products.create_index([("category", ASCENDING), ("price", DESCENDING)])

Best Practices

  1. Reuse MongoClient as a Singleton: MongoClient contains a built-in connection pool. Create it once at application startup and reuse it across requests; do not instantiate a new client per function call.
  2. Handle ObjectId Serialization: Python's standard json.dumps() cannot serialize bson.ObjectId or datetime objects directly. Use bson.json_util.dumps() or Pydantic custom serializers when returning JSON.
  3. Use Projections to Reduce Network Overhead: If you only need a user's email, fetch only that field: db.users.find({}, {"email": 1, "_id": 0}).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents