A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-mongodb-bulk_write/ below:

Python MongoDB - bulk_write() - GeeksforGeeks

Python MongoDB - bulk_write()

Last Updated : 04 Jul, 2025

bulk_write() method in PyMongo is used to perform multiple write operations (like insert, update, or delete) in a single batch. It improves performance by reducing the number of round-trips between the application and the database. This method is especially useful for handling large datasets or grouped operations efficiently.

Syntax
collection.bulk_write(requests, ordered=True)

Parameters :

Example 1

In this example, bulk_write() is used to perform a series of operations on the "myTable" collection inserting two documents, deleting one and replacing another.

python
from pymongo import MongoClient, InsertOne, DeleteOne, ReplaceOne

client = MongoClient("mongodb://localhost:27017/")
database = client['database']
mycollection = database['myTable']

# Define bulk write operations
requests = [
    InsertOne({"Student name": "Cody"}),
    InsertOne({"Student name": "Drew"}),
    DeleteOne({"Student name": "Cody"}),
    ReplaceOne({"Student name": "Drew"}, {"Student name": "Andrew"}, upsert=True)
]

# Execute the bulk write operations
result = mycollection.bulk_write(requests)

# Print final documents in the collection
print("Documents after bulk_write():")
for doc in mycollection.find():
    print(doc)

Output

Snapshot of Terminal showing Output of bulk_write()

Explanation:

Example 2

In this Example, bulk_write() is used to perform multiple operations on the "myTable" collection inserting two documents, updating one by incrementing a value and deleting another.

python
from pymongo import MongoClient, InsertOne, DeleteOne, ReplaceOne, UpdateOne

client = MongoClient("mongodb://localhost:27017/")
database = client['database']
mycollection = database['myTable'] 

# defining the bulk write requests
requests = [
    InsertOne({"x": 5}),
    InsertOne({"y": 2}),
    UpdateOne({'x': 5}, {'$inc': {'x': 3}}),  # increments x from 5 to 8
    DeleteOne({"y": 2})  # deletes the document with y = 2
]

# executing the bulk operations
result = mycollection.bulk_write(requests)

# print final documents in the collection
print("Documents after bulk_write():")
for doc in mycollection.find():
    print(doc)

Output

Snapshot of Terminal showing Output of bulk_write()

Explanation:

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