Python Tutorial
Python MongoDB - Collection
Collections are MongoDB's equivalent of tables — flexible containers for documents.
What Is a Collection?
A collection holds a group of documents, much like a table holds rows — but without a fixed schema. Different documents in the same collection can have different fields. Like databases, a collection is created lazily on first insert.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
customers = db["customers"] # referenced; created on first insertCreate It by Inserting
customers.insert_one({"name": "John", "address": "Highway 37"})
print("customers" in db.list_collection_names()) # TrueList and Check Collections
print(db.list_collection_names())
if "customers" in db.list_collection_names():
print("The collection exists.")Explicit Creation and Validation
Usually you let inserts create collections, but you can create one explicitly to set options like a schema validator or a capped size.
db.create_collection(
"logs",
capped=True, size=100_000, max=1000) # ring buffer of 1000 docs
# schema validation: reject documents missing required fields
db.create_collection("users", validator={
"$jsonSchema": {
"bsonType": "object",
"required": ["email"],
"properties": {"email": {"bsonType": "string"}},
}
})Indexes Belong to Collections
Indexes make queries fast. Create them on fields you filter or sort by frequently.
customers.create_index("name") # single field
customers.create_index([("email", 1)], unique=True) # unique index
print(customers.index_information())A unique=True index enforces uniqueness (like a SQL UNIQUE constraint) — a second insert with the same value raises DuplicateKeyError.
Dropping a Collection
customers.drop() # removes the collection and all its documentsBest Practices
- Group related documents in one collection; keep unrelated data in separate collections.
- Add indexes for fields you query or sort on often.
- Use schema validation when you need to guarantee document structure.
- Even schema-less, keep field names and shapes consistent for sane queries.
Try It Yourself
Exercise 1: Create a unique index on the email field of a collection.
Show solution
users = client["app"]["users"]
users.create_index("email", unique=True)Exercise 2: True or false: documents in one collection must all have the same fields.
Show solution
False — collections are schema-less, so documents can have different fields (though consistency is good practice).
📘 Real-World Deep Dive
Knowing <strong>MongoDB Collection (MongoDB)</strong> well is what turns MongoDB from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of MongoDB Collection that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from pymongo import MongoClient
c = MongoClient()
db = c.shop
db.create_collection("orders")
print(db.list_collection_names())Expected Output
(see source)Common mistakes
- Inserting a
dictwith embeddeddatetimeworks, but naivedatetime(without UTC) leads to subtle comparison bugs. - Queries with type-mismatched values silently return no results — cast at the boundary or use
bsoncodecs. find()returns a cursor — calllist(cursor)only once you intend to materialise results.- Treating MongoDB Collection as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Project only the fields you need:
collection.find({}, {"name": 1}). - Use
bulk_writeinstead of looping over single inserts / updates — order-of-magnitude faster. - Create indexes:
collection.create_index([("field", pymongo.ASCENDING)]). - When working with MongoDB, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.