W3docs

MongoDB Create Database

Learn how to create a MongoDB database in Python using PyMongo. Covers connecting to MongoDB, lazy creation, listing databases, and gotchas.

MongoDB does not create a database until you actually write data into it. This "lazy creation" behaviour is intentional and is one of the first things new users stumble over. This chapter walks you through connecting to a MongoDB server with Python's pymongo driver, understanding when a database is actually created, verifying that it exists, and cleaning up test databases.

Prerequisites

  • Python 3.8 or later installed
  • A running MongoDB server (local or remote). If you have not installed MongoDB yet, follow the MongoDB Get Started chapter first.
  • The pymongo driver installed:
pip install pymongo

How MongoDB Database Creation Works

Unlike relational databases, you never run a CREATE DATABASE statement in MongoDB. Instead:

  1. You reference a database by name through the client object.
  2. MongoDB holds that reference in memory but creates nothing on disk yet.
  3. The database is physically created the first time you insert a document or explicitly create a collection.

This means client["mydb"] is always "successful" — it returns a Database object whether mydb exists or not.

Connecting to MongoDB

Import MongoClient and open a connection. When MongoDB is running on the same machine with default settings (host localhost, port 27017), you can call MongoClient() with no arguments:

from pymongo import MongoClient

# Connect to the local MongoDB server (localhost:27017)
client = MongoClient()

To connect to a remote server or a non-default port, pass a connection URI:

# Generic URI form
client = MongoClient("mongodb://hostname:port")

# Example: remote host on port 27017
client = MongoClient("mongodb://db.example.com:27017")

# Example: with authentication
client = MongoClient("mongodb://username:[email protected]:27017")

MongoClient uses a connection pool internally — you create one client per application and reuse it across all database operations.

Getting a Database Reference

Access a database by attribute name or dictionary-style key notation:

# Both lines do exactly the same thing
db = client.my_database
db = client["my_database"]

Use the dictionary style (client["name"]) when the database name contains characters that are not valid Python identifiers, such as hyphens.

At this point the database does not exist yet on the server. Print the client's database list to confirm:

print(client.list_database_names())
# Typical output: ['admin', 'config', 'local']
# 'my_database' is NOT listed yet

Creating the Database by Inserting a Document

The simplest way to materialise the database is to insert one document. The example below creates a database called bookstore and a collection called books:

from pymongo import MongoClient

client = MongoClient()

db = client["bookstore"]
books = db["books"]

# Inserting the first document triggers physical database creation
result = books.insert_one({
    "title": "The Pragmatic Programmer",
    "author": "David Thomas",
    "year": 1999
})

print("Inserted document id:", result.inserted_id)
print("Databases now:", client.list_database_names())

After running this script you should see output similar to:

Inserted document id: 64a1e3b2c9f1234567890abc
Databases now: ['admin', 'bookstore', 'config', 'local']

bookstore now appears in the list because at least one document exists in it.

Verifying Whether a Database Exists

Because a referenced database may or may not exist, checking requires inspecting the list returned by list_database_names():

from pymongo import MongoClient

client = MongoClient()

def database_exists(client, name):
    return name in client.list_database_names()

print(database_exists(client, "bookstore"))   # True (if created above)
print(database_exists(client, "no_such_db"))  # False

Dropping a Test Database

When you want to remove a database (for example after testing), call drop_database() on the client:

from pymongo import MongoClient

client = MongoClient()
client.drop_database("bookstore")

print("bookstore" in client.list_database_names())  # False

This permanently deletes the database and all its collections and documents. There is no confirmation prompt.

Common Gotchas

Typos are silent

Because MongoDB creates databases on demand, a typo in the database name silently creates a second database instead of raising an error:

# Intended: 'bookstore'
# Actual:   'bookstoree'  — a new empty database that never gets data
db = client["bookstoree"]

Always define database names as constants at the top of your module to prevent this:

DB_NAME = "bookstore"
db = client[DB_NAME]

Empty databases are invisible

If you reference a database but never insert data, list_database_names() will not include it. This can make debugging confusing — the database "exists" as a Python object but not on disk.

Connection errors surface late

MongoClient() succeeds even when MongoDB is not running. The connection error surfaces only when you make an actual request (insert, find, etc.). Wrap real operations in a try/except block:

from pymongo import MongoClient
from pymongo.errors import ConnectionFailure

client = MongoClient(serverSelectionTimeoutMS=3000)

try:
    # This forces a real network round-trip
    client.admin.command("ping")
    print("Connected to MongoDB")
except ConnectionFailure as e:
    print("Could not connect:", e)

Full Working Example

The following self-contained script demonstrates all the steps covered in this chapter:

from pymongo import MongoClient
from pymongo.errors import ConnectionFailure

DB_NAME = "demo_bookstore"

def main():
    client = MongoClient(serverSelectionTimeoutMS=3000)

    # Verify the connection
    try:
        client.admin.command("ping")
    except ConnectionFailure as e:
        print("MongoDB is not reachable:", e)
        return

    # Before any insert, the database does not appear in the list
    print("Before insert:", DB_NAME in client.list_database_names())

    db = client[DB_NAME]
    books = db["books"]

    # Insert a document — this creates the database
    books.insert_one({"title": "Clean Code", "author": "Robert C. Martin"})

    # Now the database is visible
    print("After insert: ", DB_NAME in client.list_database_names())
    print("Databases:    ", client.list_database_names())

    # Clean up
    client.drop_database(DB_NAME)
    print("After drop:   ", DB_NAME in client.list_database_names())

if __name__ == "__main__":
    main()

Expected output (document id will differ):

Before insert: False
After insert:  True
Databases:     ['admin', 'config', 'demo_bookstore', 'local']
After drop:    False

Next Steps

Was this page helpful?