Last Updated : 12 Jul, 2025
In PyMongo, document insertion and replacement are performed using insert_one(), insert_many() and replace_one(). These methods allow you to add new documents or completely replace existing ones based on a matching filter.
Syntaxcollection.insert_one(document)
collection.insert_many([document1, document2, ...])
collection.replace_one(filter, replacement, upsert=False)
Parameters:
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c['companyDB']
col = db['employees']
data = [
{"_id": 1, "name": "Alice", "department": "HR"},
{"_id": 2, "name": "Bob", "department": "Engineering"},
{"_id": 3, "name": "Charlie", "department": "Marketing"}
]
col.delete_many({})
col.insert_many(data)
print("Data inserted.")
Output
Sample dataData inserted.
Explanation:
Example 1: Insert a single document
Python
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c['companyDB']
col = db['employees']
col.insert_one({"_id": 4, "name": "David", "department": "Sales"})
print("Document inserted.")
Output
Document inserted.
Output
Single document addedExplanation: Adds one employee document with a unique _id.
Example 2: Insert multiple documents
Python
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c['companyDB']
col = db['employees']
more_emp = [
{"_id": 5, "name": "Eve", "department": "IT"},
{"_id": 6, "name": "Frank", "department": "Finance"}
]
col.insert_many(more_emp)
print("2 documents inserted.")
Output
Batch insert done2 documents inserted.
Explanation: insert_many() is used for inserting multiple documents in one call.
Example 3: Replace an existing document
Python
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c['companyDB']
col = db['employees']
res = col.replace_one(
{"name": "Bob"},
{"_id": 2, "name": "Bobby", "department": "Engineering", "status": "Active"}
)
print(f"Matched: {res.matched_count}, Modified: {res.modified_count}")
Output
Document replacedMatched: 1, Modified: 1
Explanation: The document where name is "Bob" is completely replaced. Only the fields in the replacement document will remain.
Example 4: Use replace_one()
with upsert=True
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c['companyDB']
col = db['employees']
res = col.replace_one(
{"name": "Zara"},
{"_id": 10, "name": "Zara", "department": "Support"},
upsert=True
)
print(f"Matched: {res.matched_count}, Modified: {res.modified_count}, Upserted ID: {res.upserted_id}")
Output
Upsert triggeredMatched: 0, Modified: 0, Upserted ID: 10
Explanation: No document matches name = "Zara", so replace_one() with upsert=True inserts a new document with _id: 10.
Related Articles
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4