![]() |
VOOZH | about |
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.
collection.insert_one(document)
collection.insert_many([document1, document2, ...])
collection.replace_one(filter, replacement, upsert=False)
Parameters:
Output
Data inserted.
Explanation:
Example 1: Insert a single document
Output
Document inserted.
Output
Explanation: Adds one employee document with a unique _id.
Example 2: Insert multiple documents
Output
2 documents inserted.
Explanation: insert_many() is used for inserting multiple documents in one call.
Example 3: Replace an existing document
Output
Matched: 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
Output
Matched: 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