VOOZH about

URL: https://www.geeksforgeeks.org/python/mongodb-python-insert-replace_one-replace_many/

⇱ MongoDB Python - Insert and Replace Operations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

MongoDB Python - Insert and Replace Operations

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.

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.

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

Output

Document inserted.

Output

👁 Output
Single document added

Explanation: Adds one employee document with a unique _id.

Example 2: Insert multiple documents

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

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

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

Comment