Open In App

MongoDB Python - Insert and Replace Operations

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Syntax

collection.insert_one(document)
collection.insert_many([document1, document2, ...])
collection.replace_one(filter, replacement, upsert=False)

Parameters:

  • document: Dictionary to insert into the collection.
  • filter: Criteria to find the document to replace.
  • replacement: New document to fully replace the matched one.
  • upsert (optional): If True, inserts a new document if no match is found (default is False).

Here is our sample data.

Python
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

Data inserted.

Output
Sample data

Explanation:

  • MongoClient() connects to the local server and selects companyDB.employees.
  • insert_many(data) adds sample employee documents.
  • delete_many({}) clears the collection to avoid duplicate data.

Examples

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

Output
Single document added

Explanation: 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

2 documents inserted.

Output
Batch insert done

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

Matched: 1, Modified: 1

Outputguhg
Document replaced

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

Python
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

Matched: 0, Modified: 0, Upserted ID: 10

Output
Upsert triggered

Explanation: No document matches name = "Zara", so replace_one() with upsert=True inserts a new document with _id: 10.

Related Articles


Next Article
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy