Python MongoDB Create Database
Learn how to create and manage MongoDB databases with Python
đī¸ Creating MongoDB Databases
In MongoDB, databases are created automatically when you first store data in them. You don't need to explicitly create a database - just start using it!
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Create/access database (created when first document is inserted)
db = client["mystore"]
print(f"Database '{db.name}' is ready to use!")
Database Creation Concepts
Lazy Creation
Databases are created when first used
# Database created when first document inserted
db = client["newstore"]
collection = db["products"]
Naming Rules
Database names have specific rules
# Valid names
db1 = client["mystore"]
db2 = client["user_data"]
db3 = client["app2024"]
List Databases
View all existing databases
# List all databases
db_list = client.list_database_names()
print("Databases:", db_list)
Check Existence
Verify if database exists
# Check if database exists
if "mystore" in client.list_database_names():
print("Database exists!")
đ¨ Creating a Database
MongoDB creates databases automatically when you first insert data
đš Basic Database Creation
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Access/create database
db = client["bookstore"]
# Database is not actually created until you insert data
print(f"Database object created: {db.name}")
# Check if database exists (will be False until data is inserted)
db_exists = "bookstore" in client.list_database_names()
print(f"Database exists on server: {db_exists}") # False
# Insert first document to actually create the database
books = db["books"]
first_book = {"title": "Python Guide", "author": "John Smith", "price": 29.99}
result = books.insert_one(first_book)
# Now database exists
db_exists = "bookstore" in client.list_database_names()
print(f"Database exists after insert: {db_exists}") # True
đš Multiple Database Creation
# Create multiple databases by inserting data
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Create inventory database
inventory_db = client["inventory"]
products = inventory_db["products"]
products.insert_one({"name": "Laptop", "stock": 50})
# Create users database
users_db = client["users"]
customers = users_db["customers"]
customers.insert_one({"name": "Alice", "email": "[email protected]"})
# Create orders database
orders_db = client["orders"]
orders = orders_db["orders"]
orders.insert_one({"customer_id": 1, "total": 999.99})
print("Created 3 databases with initial data!")
đ Database Naming Rules
MongoDB has specific rules for database names
â Valid Database Names
- Can contain letters, numbers, and underscores
- Cannot start with a number
- Case sensitive
- Maximum 64 characters
â Invalid Characters
- Spaces, slashes (/), backslashes (\)
- Dots (.), quotes, asterisks (*)
- Reserved names: admin, local, config
# Good database names
good_names = [
"mystore",
"user_data",
"app2024",
"inventory_system",
"blogDB"
]
# Bad database names (avoid these)
bad_names = [
"my store", # Contains space
"data/base", # Contains slash
"app.db", # Contains dot
"123store", # Starts with number
"admin" # Reserved name
]
# Create databases with good names
client = pymongo.MongoClient("mongodb://localhost:27017/")
for name in good_names:
db = client[name]
# Insert dummy data to create database
db["test"].insert_one({"created": True})
print(f"â
Created database: {name}")
print(f"Total databases: {len(client.list_database_names())}")
đ Listing Databases
View and manage existing databases
đš List All Databases
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Get list of database names
db_names = client.list_database_names()
print("Available databases:")
for db_name in db_names:
print(f" - {db_name}")
# Get detailed database information
db_info = client.list_databases()
print("\nDetailed database info:")
for db in db_info:
print(f"Name: {db['name']}, Size: {db.get('sizeOnDisk', 'N/A')} bytes")
đš Check Database Existence
# Function to check if database exists
def database_exists(client, db_name):
return db_name in client.list_database_names()
# Check multiple databases
databases_to_check = ["mystore", "inventory", "nonexistent"]
for db_name in databases_to_check:
exists = database_exists(client, db_name)
status = "â
EXISTS" if exists else "â NOT FOUND"
print(f"Database '{db_name}': {status}")
# Create database if it doesn't exist
def create_database_if_not_exists(client, db_name):
if not database_exists(client, db_name):
db = client[db_name]
# Insert dummy document to create database
db["_temp"].insert_one({"created": True})
# Remove dummy document
db["_temp"].delete_one({"created": True})
print(f"â
Created database: {db_name}")
else:
print(f"âšī¸ Database '{db_name}' already exists")
create_database_if_not_exists(client, "newstore")
đ¯ Practical Example: E-commerce Setup
Create a complete database structure for an e-commerce application
import pymongo
from datetime import datetime
def setup_ecommerce_database():
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Create main e-commerce database
ecommerce_db = client["ecommerce_store"]
# Create collections with sample data
# 1. Products collection
products = ecommerce_db["products"]
sample_products = [
{"name": "Laptop", "price": 999.99, "category": "Electronics", "stock": 25},
{"name": "Book", "price": 19.99, "category": "Education", "stock": 100},
{"name": "Shirt", "price": 29.99, "category": "Clothing", "stock": 50}
]
products.insert_many(sample_products)
# 2. Customers collection
customers = ecommerce_db["customers"]
sample_customers = [
{"name": "John Doe", "email": "[email protected]", "joined": datetime.now()},
{"name": "Jane Smith", "email": "[email protected]", "joined": datetime.now()}
]
customers.insert_many(sample_customers)
# 3. Orders collection
orders = ecommerce_db["orders"]
sample_order = {
"customer_email": "[email protected]",
"items": [{"product": "Laptop", "quantity": 1, "price": 999.99}],
"total": 999.99,
"date": datetime.now(),
"status": "pending"
}
orders.insert_one(sample_order)
# Verify database creation
if "ecommerce_store" in client.list_database_names():
print("â
E-commerce database created successfully!")
# Show collections
collections = ecommerce_db.list_collection_names()
print(f"đ Collections created: {collections}")
# Show document counts
print(f"đ Products: {products.count_documents({})}")
print(f"đ Customers: {customers.count_documents({})}")
print(f"đ Orders: {orders.count_documents({})}")
return ecommerce_db
# Run the setup
db = setup_ecommerce_database()