Python MongoDB Insert Document – A Complete Guide

Last updated 4 weeks, 1 day ago | 101 views 75     5

Tags:- Python MongoDB

MongoDB is a popular NoSQL database known for its flexibility and scalability. When working with MongoDB in Python, the pymongo library provides an intuitive API for interacting with your databases and collections.

In this article, you'll learn how to insert one or multiple documents into MongoDB using Python, with best practices and examples.


Prerequisites

✅ 1. Install MongoDB

You need MongoDB running locally or on a cloud provider like MongoDB Atlas.

✅ 2. Install pymongo (MongoDB Python driver)

pip install pymongo

Connecting to MongoDB in Python

from pymongo import MongoClient

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

# Access or create a database
db = client["mydatabase"]

# Access or create a collection
collection = db["customers"]

You now have access to the customers collection in mydatabase.


Inserting a Single Document

Use the insert_one() method:

document = {
    "name": "John Doe",
    "email": "[email protected]",
    "age": 29
}

result = collection.insert_one(document)
print("Inserted ID:", result.inserted_id)

✅ Explanation:

  • insert_one() adds one document to the collection.

  • It returns an InsertOneResult object, which contains the inserted ID.


Inserting Multiple Documents

Use the insert_many() method:

documents = [
    {"name": "Alice", "email": "[email protected]", "age": 25},
    {"name": "Bob", "email": "[email protected]", "age": 32},
    {"name": "Charlie", "email": "[email protected]", "age": 40}
]

result = collection.insert_many(documents)
print("Inserted IDs:", result.inserted_ids)

✅ Explanation:

  • insert_many() takes a list of dictionaries (documents).

  • inserted_ids gives a list of the generated _id values for each document.


Custom _id Field

MongoDB automatically generates a unique _id, but you can also define your own:

document = {
    "_id": 1,
    "name": "Daisy",
    "email": "[email protected]"
}

collection.insert_one(document)

⚠️ Attempting to insert another document with the same _id will raise a DuplicateKeyError.


Insert If Not Exists (Upsert)

Use update_one() with upsert=True to insert a document if it doesn't exist:

collection.update_one(
    {"email": "[email protected]"},  # Search criteria
    {"$set": {"name": "Eve", "age": 26}},
    upsert=True
)

✅ Full Example

from pymongo import MongoClient

# Step 1: Connect to MongoDB
client = MongoClient("mongodb://localhost:27017/")

# Step 2: Access database and collection
db = client["shop"]
collection = db["customers"]

# Step 3: Create document(s)
new_customer = {"name": "Liam", "email": "[email protected]", "age": 30}

# Step 4: Insert document
insert_result = collection.insert_one(new_customer)

# Step 5: Confirm insertion
print("Inserted document ID:", insert_result.inserted_id)

Tips for Using insert_one() and insert_many()

Tip Reason
Always validate your data Prevents inserting malformed documents
Use inserted_id(s) Useful for referencing inserted records
Use upsert for conditional inserts Avoids duplicates
Batch with insert_many() for performance Faster than many insert_one() calls
Use _id if you want predictable keys For referencing or deduplication

⚠️ Common Pitfalls

Pitfall Solution
Duplicate _id error Don’t reuse _id, or use auto-generated ones
Wrong connection string Ensure MongoDB is running and accessible
Inserting empty documents Always pass valid dictionaries
Forgetting to convert lists of documents in insert_many() Must be list of dictionaries

Summary

Function Description
insert_one(doc) Inserts a single document
insert_many([docs]) Inserts multiple documents
inserted_id Returns _id of inserted doc
inserted_ids List of _ids for multiple inserts
_id Optional unique identifier for document
upsert=True Insert if not exists (on update)

What's Next?

  • Learn how to query documents with find() and find_one()

  • Explore updating and deleting documents

  • Use MongoDB Atlas for cloud-based databases

  • Validate data using MongoDB schema validation