Python Tutorial
Python MongoDB - Create Database
Create a database in MongoDB — and understand why it appears only after you add data.
Databases Are Created Lazily
In MongoDB you do not run a "create database" command. You simply reference a database name; MongoDB creates it for real only when you first store data in it. The same applies to collections.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"] # referenced, not yet created on diskAt this point mydatabase will not appear in list_database_names() — it is empty. It materializes the moment you insert a document.
Make It Real: Insert Something
db = client["mydatabase"]
collection = db["customers"]
collection.insert_one({"name": "John", "address": "Highway 37"})
print("mydatabase" in client.list_database_names()) # True nowCheck if a Database Exists
if "mydatabase" in client.list_database_names():
print("The database exists.")
else:
print("Not created yet (still empty).")Two Ways to Access a Database
db = client["my-database"] # bracket syntax (needed for names with dashes)
db = client.mydatabase # attribute syntax (only for simple names)Prefer bracket syntax — it works for every valid name, including those with hyphens or reserved words.
Dropping a Database
client.drop_database("mydatabase") # permanent - back up firstBest Practices
- Remember: no data means no database — insert to materialize it.
- Use bracket syntax for database and collection access.
- Plan your database/collection naming before scaling; renaming later is awkward.
- Restrict who can call
drop_database.
Try It Yourself
Exercise 1: You referenced client["shop"] but it does not appear in list_database_names(). Why?
Show solution
MongoDB creates a database lazily — only once you insert the first document. An empty database does not exist on disk yet.
Exercise 2: Make the database real by inserting one document.
Show solution
client["shop"]["items"].insert_one({"name": "pen"})📘 Real-World Deep Dive
Knowing <strong>MongoDB Create Db (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 Create Db that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from pymongo import MongoClient
from datetime import datetime, timezone
c = MongoClient("mongodb://localhost:27017")
c.shop.users.insert_one({"email": "a@b.com", "created_at": datetime.now(timezone.utc)})Expected Output
(no output)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 Create Db 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.