Python MongoDB Create Collection

Collections in MongoDB are the equivalent of tables in traditional databases. Creating a collection using Python and MongoDB is a seamless process with the pymongo library. At The Coding College, we simplify coding for everyone. Let’s explore how to create collections in MongoDB using Python!

Prerequisites

Before you begin, ensure the following:

  1. Python Installed: Download it from python.org.
  2. MongoDB Installed: Set up MongoDB from mongodb.com.
  3. Install pymongo: Install the MongoDB driver using:
pip install pymongo

Understanding MongoDB Collections

In MongoDB, a collection is a grouping of documents. You don’t need to define a collection structure (like schema in SQL); MongoDB is schema-less, allowing for flexible data storage.

Steps to Create a Collection

Unlike SQL databases, MongoDB dynamically creates collections only when data is inserted.

Step 1: Establish a Connection

Connect to the MongoDB server:

import pymongo

# Connect to the server
client = pymongo.MongoClient("mongodb://localhost:27017/")

The above command connects to a locally hosted MongoDB server running on port 27017.

Step 2: Select or Create a Database

Specify the database where the collection will be created:

# Create or access a database
db = client["mydatabase"]

If mydatabase doesn’t exist, MongoDB will create it when a collection with data is added.

Step 3: Create a Collection

Define the collection by referencing it:

# Create or access a collection
collection = db["customers"]

At this point, the collection customers exists only in memory.

Step 4: Insert Data to Persist the Collection

MongoDB creates the collection when you insert data into it:

# Insert a document into the collection
customer = {"name": "John Doe", "email": "[email protected]"}
collection.insert_one(customer)

print("Collection created and document inserted!")

Verify Collection Creation

To ensure your collection has been created, list all collections in the database:

# List collections in the database
print(db.list_collection_names())

Complete Example

Here’s a complete script demonstrating the process:

import pymongo

# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Create or access a database
db = client["company"]

# Create or access a collection
employees = db["employees"]

# Insert a document
employee_data = {"name": "Alice", "position": "Software Engineer", "salary": 85000}
employees.insert_one(employee_data)

# Verify the collection
print("Collections in 'company':", db.list_collection_names())

MongoDB Collection Naming Rules

When naming a collection:

  1. Use alphanumeric characters, underscores (_), or hyphens (-).
  2. Avoid names with special characters or reserved keywords.
  3. Use meaningful names that describe the stored data.

Exercises

  1. Create a Collection: Create a collection named products in a database called store. Insert 5 product records.
  2. List Collections: Write a script to list all collections in a database.
  3. Dynamic Collection Names: Create collections dynamically based on user input.

Common Errors

  1. Collection Not Found:
    • Collections are only created when data is inserted.
  2. Connection Issues:
    • Ensure MongoDB is running and the connection string is correct.

Benefits of MongoDB Collections

MongoDB’s flexible collections allow developers to store diverse data types without predefined schemas. This adaptability makes it a favorite for modern applications.

Leave a Comment