Python MongoDB Tutorial – How to Create a Database with PyMongo

Last updated 5 months, 1 week ago | 452 views 75     5

Tags:- Python MongoDB

MongoDB is a popular NoSQL database that allows flexible, schema-less data storage using documents. In this tutorial, you'll learn how to create a MongoDB database using Python with the help of the PyMongo library.


Table of Contents

  1. What is PyMongo?

  2. Prerequisites

  3. Installing PyMongo

  4. Connecting to MongoDB

  5. Creating a MongoDB Database

  6. Creating a Collection (Table)

  7. Inserting Data (Triggers Database Creation)

  8. Checking if Database Was Created

  9. Full Working Example

  10. Tips and Common Pitfalls


1. What is PyMongo?

PyMongo is the official Python driver for MongoDB. It allows Python programs to connect to MongoDB databases and perform operations such as insert, update, delete, and query.


✅ 2. Prerequisites

Before starting, make sure you have:

  • Python 3 installed

  • MongoDB installed and running (locally or on MongoDB Atlas)

  • Basic Python knowledge


3. Installing PyMongo

Use pip to install PyMongo:

pip install pymongo

4. Connecting to MongoDB

You need to establish a connection before creating a database.

Connect to Localhost:

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")

Connect to MongoDB Atlas (Cloud):

client = pymongo.MongoClient("mongodb+srv://username:[email protected]/?retryWrites=true&w=majority")

Replace username, password, and cluster0.mongodb.net with your actual MongoDB Atlas credentials.


5. Creating a MongoDB Database

To create a new database, simply assign it to a variable:

db = client["mydatabase"]

⚠️ Note: MongoDB does not create the database until you insert data into it.


6. Creating a Collection (Table Equivalent)

Now create a collection within the database:

collection = db["customers"]

This is similar to creating a table in relational databases.


✍️ 7. Inserting Data (Triggers Database Creation)

To trigger the actual creation of the database and collection, you must insert at least one document.

customer = {"name": "Alice", "email": "[email protected]"}
collection.insert_one(customer)

After this insertion, both the database (mydatabase) and the collection (customers) will be created.


8. Checking if Database Was Created

To verify the database:

print(client.list_database_names())

If 'mydatabase' appears in the list, the database was successfully created.


9. Full Working Example

import pymongo

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

# Create database and collection
db = client["mydatabase"]
collection = db["customers"]

# Insert document (this triggers actual creation)
data = {"name": "Alice", "email": "[email protected]"}
collection.insert_one(data)

# Verify
print("Databases:", client.list_database_names())
print("Collections in mydatabase:", db.list_collection_names())

Output:

Databases: ['admin', 'config', 'local', 'mydatabase']
Collections in mydatabase: ['customers']

10. Tips and Common Pitfalls

Issue Solution
Database doesn’t show up Insert at least one document to trigger creation
PyMongo not installed Run pip install pymongo
Connection error Ensure MongoDB server is running locally or Atlas URI is correct
Duplicate _id errors Avoid inserting documents with existing _id values unless intended
Forgetting to check database Use list_database_names() to confirm creation

Conclusion

Creating a database in MongoDB using Python is simple and efficient. With just a few lines of code using PyMongo, you can establish a connection, create a database, define a collection, and insert data.

This flexibility makes MongoDB a powerful choice for modern Python applications that require dynamic and scalable data storage.