Python - MongoDB

Overview

Estimated time: 20–30 minutes

Use pymongo to connect to MongoDB, perform CRUD operations, and design indexes for performance.

Learning Objectives

  • Connect with a connection string and select databases/collections.
  • Insert, query, update, and delete documents with filters.
  • Create indexes and understand their impact.

Examples

# pip install pymongo
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017")
db = client["appdb"]
users = db["users"]
users.insert_one({"name": "Ada", "tags": ["admin"]})
print(list(users.find({"name": "Ada"})))

Guidance & Patterns

  • Use ObjectId for primary keys; store only necessary nested structures.
  • Define indexes on frequent query fields.

Best Practices

  • Validate inputs; avoid unbounded queries without filters.
  • Keep credentials out of source; use env vars or secret stores.

Exercises

  1. Add a compound index for (name, tag) and demonstrate its use.
  2. Implement a simple pagination query using skip/limit.