Back to Python Notes
Topic #296

Create Collection

Learn how to create and access collections in MongoDB using the PyMongo library, enabling you to store and retrieve documents efficiently.

What it is

In MongoDB, a collection is a group of related documents, similar to a table in a relational database. When using Python with the pymongo library, you do not explicitly "create" a collection before inserting data. Instead, collections are created implicitly when you first insert a document into them. Accessing a collection via db["name"] or db.name returns a Collection object that acts as an interface for interacting with that specific set of documents.

Key terms include Database (the container for collections), Document (a JSON-like record), and Collection (the namespace where documents live).

Why it matters

  • Organization: Collections allow you to logically separate different types of data (e.g., users, products, logs) within a single database.
  • Simplicity: The implicit creation model reduces boilerplate code; you don't need schema migration scripts to add new data structures.
  • Performance: Indexes can be applied at the collection level, optimizing query speeds for specific datasets.
  • Scalability: Different collections can have different storage engines or sharding strategies if needed.

Syntax or steps

To work with a collection, you must first establish a connection to the database. Then, you reference the collection by name. If the collection does not exist, MongoDB creates it automatically upon the first write operation.

  1. Connect to the MongoDB server using MongoClient.
  2. Select a database using bracket notation or dot notation.
  3. Select a collection from the database object.
  4. Insert a document to trigger the actual creation of the collection on disk.

Example

from pymongo import MongoClient

# 1. Connect to the local MongoDB instance
client = MongoClient("mongodb://localhost:27017/")

# 2. Select the database (created implicitly if missing)
db = client["my_database"]

# 3. Reference the collection (object exists in memory, but not yet on disk)
col = db["users"]

# 4. Insert a document to actually create the collection in the DB
user_data = {"name": "Alice", "age": 30}
result = col.insert_one(user_data)

print(f"Inserted ID: {result.inserted_id}")
print(f"Collections in DB: {db.list_collection_names()}")

Explanation: Line 5 connects to the server. Line 8 selects the database. Line 11 assigns the users collection to the variable col. At this point, no network call is made to check existence. Line 14 inserts a dictionary. This triggers the creation of the users collection in my_database. Finally, we verify the insertion and list existing collections.

Common mistakes

  • Assuming immediate persistence: Referencing db["new_col"] does not create anything until data is written. Do not expect list_collection_names() to show empty collections.
  • Invalid names: Collection names cannot contain null characters, start with system., or use certain reserved prefixes depending on the version. Stick to alphanumeric characters and underscores.
  • Case sensitivity: db.Users and db.users are two distinct collections. Be consistent with naming conventions.
  • Forgetting to close connections: In long-running applications, ensure clients are properly managed to avoid resource leaks, though modern drivers handle pooling well.

When to use it

Use explicit collection references when you know the structure ahead of time. Use dynamic collection names only if necessary (e.g., logging per day), as this can lead to performance issues due to too many namespaces.

Approach Best For Risk
Static Name (db["logs"]) Standard application data Low
Dynamic Name (db[f"logs_{date}"]) Time-series partitioning High (namespace limit)

Practice

Guided Exercise: Create a script that connects to a database named test_db, accesses a collection named products, and inserts three different product dictionaries. Print the count of documents in the collection after insertion.

Challenge: Modify the script to check if the collection products exists before inserting. Hint: Use db.list_collection_names() or attempt a read operation first.

Quick check

Question: Does executing col = db["orders"] create a new collection in the MongoDB database?

Answer: No. It only creates a Python object representing the collection. The actual MongoDB collection is created only when the first document is inserted.

Summary

Collections in PyMongo are accessed via simple attribute or bracket notation on the database object. They are created lazily upon the first write operation, allowing for flexible and schema-less data organization. Understanding this implicit behavior prevents confusion about why empty collections do not appear in listings.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Create Collection – FAQs

Quick answers about learning Create Collection in Python.

This free note from Coding Now Tech Institute explains Create Collection in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Create Collection, is 100% free with no signup required.
With focused practice, most students grasp Create Collection in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now