Python MongoDB Tutorial – How to Insert a Document Using PyMongo

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

Tags:- Python MongoDB

MongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like documents. In this tutorial, you'll learn how to insert documents into a MongoDB collection using Python with the PyMongo library.

Whether you're working with a local MongoDB instance or a cloud-based MongoDB Atlas cluster, this guide covers all the basics with step-by-step explanations and code examples.


Table of Contents

  1. What is a MongoDB Document?

  2. Why Use PyMongo?

  3. Prerequisites

  4. Installing PyMongo

  5. Connecting to MongoDB

  6. Creating a Database and Collection

  7. Inserting One Document

  8. Inserting Multiple Documents

  9. Verifying Insertions

  10. Full Working Example

  11. Tips and Common Pitfalls


1. What is a MongoDB Document?

A document in MongoDB is a set of key-value pairs, similar to a Python dictionary or a JSON object. For example:

{
  "name": "Alice",
  "email": "[email protected]",
  "age": 25
}

Documents are stored in collections, which are similar to tables in relational databases.


2. Why Use PyMongo?

PyMongo is the official MongoDB driver for Python. It lets you:

  • Connect to MongoDB databases (local or cloud)

  • Perform CRUD operations (Create, Read, Update, Delete)

  • Work with Python dictionaries for document data


⚙️ 3. Prerequisites

  • Python 3 installed

  • MongoDB server (local or MongoDB Atlas)

  • Basic understanding of Python and JSON


4. Installing PyMongo

Install PyMongo using pip:

pip install pymongo

5. Connecting to MongoDB

Local MongoDB Server:

import pymongo

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

MongoDB Atlas (Cloud):

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

Replace username, password, and cluster.mongodb.net with your actual credentials.


6. Creating a Database and Collection

db = client["mydatabase"]               # Create or access the database
collection = db["users"]               # Create or access the collection

7. Inserting One Document

Use the insert_one() method:

user = {"name": "Alice", "email": "[email protected]", "age": 25}
result = collection.insert_one(user)

print("Inserted ID:", result.inserted_id)

Explanation:

  • insert_one() returns an object containing the _id of the inserted document.

  • MongoDB automatically adds an _id field if it's not provided.


8. Inserting Multiple Documents

Use the insert_many() method for batch insertion:

users = [
    {"name": "Bob", "email": "[email protected]", "age": 30},
    {"name": "Charlie", "email": "[email protected]", "age": 28}
]

result = collection.insert_many(users)

print("Inserted IDs:", result.inserted_ids)

✅ 9. Verifying Insertions

To confirm your documents were inserted:

for user in collection.find():
    print(user)

You can also filter:

user = collection.find_one({"name": "Alice"})
print(user)

10. Full Working Example

import pymongo

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

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

# Insert one document
user = {"name": "Alice", "email": "[email protected]", "age": 25}
result_one = collection.insert_one(user)
print("Inserted one ID:", result_one.inserted_id)

# Insert multiple documents
users = [
    {"name": "Bob", "email": "[email protected]", "age": 30},
    {"name": "Charlie", "email": "[email protected]", "age": 28}
]
result_many = collection.insert_many(users)
print("Inserted many IDs:", result_many.inserted_ids)

# Verify insertion
print("All users in database:")
for user in collection.find():
    print(user)

11. Tips and Common Pitfalls

Tip / Pitfall Advice
MongoDB auto-generates _id You can also manually set _id, but ensure it's unique
Inconsistent data formats MongoDB allows schema-less data; maintain consistency yourself
Duplicate key error Avoid inserting documents with duplicate _id
Empty insert Don't call insert_many([]) – it will raise an error
Connection error Ensure MongoDB is running locally or credentials are correct for Atlas

Conclusion

Inserting documents into MongoDB using Python is straightforward with PyMongo. Whether you're inserting a single document or multiple records at once, the process is intuitive and efficient.

This flexibility makes MongoDB a strong choice for Python developers building scalable, dynamic applications.