Creating MongoDB Collections with Python
Learn how to create MongoDB collections in Python using pymongo — explicit and implicit creation, capped collections, validators, and listing collections.
A collection is MongoDB's equivalent of a table in a relational database. It holds a group of documents (JSON-like objects) and belongs to a single database. This chapter shows you two ways to create a collection with Python's pymongo driver — explicitly with create_collection() and implicitly by inserting the first document — along with collection options such as capped collections and schema validators.
Prerequisites
Before continuing, make sure you have:
- Python 3.7 or later installed
pymongoinstalled (pip install pymongo)- A running MongoDB instance — either MongoDB Atlas (cloud) or a local server started with
mongod
See MongoDB Get Started for the full setup walkthrough and MongoDB Create Database for how databases work in MongoDB.
Connecting to MongoDB
Every collection lives inside a database, so the first step is always to obtain a database handle.
Connect to a local MongoDB server and select a database
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mystore"] # selects (or lazily creates) the databaseTo connect to MongoDB Atlas, replace the connection string with the one from your Atlas dashboard:
client = pymongo.MongoClient(
"mongodb+srv://<username>:<password>@cluster0.example.mongodb.net/"
)
db = client["mystore"]Replace <username>, <password>, and the host with your actual credentials.
Explicit Collection Creation
Use create_collection() when you need to control collection options at creation time (capped size, schema validation, collation, etc.).
Create a collection explicitly
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mystore"]
collection = db.create_collection("customers")
print("Collection created:", collection.name)
# Collection created: customerscreate_collection() raises pymongo.errors.CollectionInvalid if a collection with that name already exists. Guard against this with a try/except:
Handle the case where the collection already exists
from pymongo.errors import CollectionInvalid
try:
collection = db.create_collection("customers")
print("Created:", collection.name)
except CollectionInvalid:
print("Collection already exists — using existing one")
collection = db["customers"]Collection Naming Rules
MongoDB collection names must:
- Not be an empty string
- Not contain
$or the null character (\0) - Not start with
system.(that prefix is reserved) - Not exceed 120 bytes when combined with the database name and a dot separator
Valid names: customers, order_items, 2024_logs. Invalid names: $orders, system.users.
Implicit Collection Creation
The most common approach in day-to-day development is to let MongoDB create the collection automatically when you insert the first document. If the collection does not exist, MongoDB creates it on the fly.
Create a collection implicitly by inserting a document
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mystore"]
products = db["products"] # no round-trip to the server yet
result = products.insert_one({"name": "Widget", "price": 9.99, "stock": 100})
print("Inserted ID:", result.inserted_id)
# Inserted ID: 6650a1b2c3d4e5f678901234 (an ObjectId — yours will differ)The assignment db["products"] is purely local; MongoDB only creates the collection when the insert_one() call hits the server.
Capped Collections
A capped collection is a fixed-size circular buffer. Once it reaches its size limit, MongoDB overwrites the oldest documents automatically. This makes capped collections ideal for logs, audit trails, and event streams.
Create a capped collection (max 1 MB, max 1000 documents)
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mystore"]
logs = db.create_collection(
"access_logs",
capped=True,
size=1_048_576, # maximum size in bytes (1 MB) — required for capped collections
max=1000, # optional: maximum number of documents
)
print("Capped collection created:", logs.name)
# Capped collection created: access_logsKey capped-collection rules:
sizeis mandatory whencapped=True;maxis optional.- You cannot shard a capped collection.
- Documents in a capped collection cannot grow beyond their original size on update (padding is added automatically, but the slot size is fixed).
Adding a Schema Validator
MongoDB's schema validation lets you enforce document structure at the database level. Validation rules are expressed as JSON Schema.
Create a collection with a JSON Schema validator
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mystore"]
validator = {
"$jsonSchema": {
"bsonType": "object",
"required": ["name", "price"],
"properties": {
"name": {"bsonType": "string", "description": "must be a string"},
"price": {"bsonType": "double", "description": "must be a number"},
"stock": {"bsonType": "int", "description": "must be an integer"},
},
}
}
orders = db.create_collection("orders", validator=validator)
print("Collection with validator created:", orders.name)
# Collection with validator created: ordersWhen validationAction is the default ("error"), MongoDB rejects any insert or update that violates the schema. Set it to "warn" to log violations without rejecting writes.
Listing Collections
To see which collections exist in a database, use list_collection_names(). This is also a handy way to check whether a collection already exists before calling create_collection().
List all collections in a database
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mystore"]
names = db.list_collection_names()
print(names)
# ['customers', 'products', 'orders', 'access_logs']Check whether a collection exists before creating it
if "customers" not in db.list_collection_names():
db.create_collection("customers")
print("Created customers collection")
else:
print("customers already exists")list_collection_names() returns a plain Python list, so any list operation works on the result.
Choosing Explicit vs. Implicit Creation
| Situation | Recommended approach |
|---|---|
| You need capped size, a validator, or a custom collation | create_collection() with options |
| You want to guarantee the collection exists before writing | create_collection() + CollectionInvalid guard |
| You just need a place to store documents quickly | Implicit — insert a document and let MongoDB create the collection |
| You want to check existence without creating | list_collection_names() |
Next Steps
Now that you have a collection, you can start working with documents:
- MongoDB Insert — add single and multiple documents with
insert_one()andinsert_many() - MongoDB Find — query documents from a collection
- MongoDB Drop Collection — delete a collection when you no longer need it