Python MongoDB - bulk_write()
Last Updated :
10 Jul, 2020
Improve
MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. Refer to MongoDB: An Introduction for a much more detailed introduction on MongoDB. Now let's understand the Bulk Write operation in MongoDB using Python.
bulk_write()
The PyMongo function bulk_write() sends a batch of write operations to the server. Executing write operations in batches increases the write throughput.
Syntax : bulk_write(requests, ordered = True, bypass_document_validation = False, session = None) Parameters :Example 1 : Executing multiple requests using
- requests : Requests are passed as a list of write operation instances.
- ordered : (Optional) A boolean specifying whether the operation executions are performed in an ordered or unordered manner. By default, it is set to True.
- bypass_document_validation : (Optional) A value indicating whether to bypass document validation.
- session : (Optional) a ClientSession.
bulk_write().
# importing the module
from pymongo import MongoClient, InsertOne, DeleteOne, ReplaceOne
# creating a MongoClient object
client = MongoClient()
# connecting with the portnumber and host
client = MongoClient("mongodb://localhost:27017/")
# accessing the database
database = client['database']
# access collection of the database
mycollection = mydatabase['myTable']
# defining the requests
requests = [InsertOne({"Student name": "Cody"}),
InsertOne({ "Student name": "Drew"}),
DeleteOne({"Student name": "Cody"}),
ReplaceOne({"Student name": "Drew"},
{ "Student name": "Andrew"}, upsert = True)]
# executing the requests
result = mycollection.bulk_write(requests)
for doc in mycollection.find({}):
print(doc)
Output :
{'_id': ObjectId('5f060aa5a9666ecd86f5b6bd'), 'Student name': 'Andrew'}
Example 2 :
# importing the modules
from pymongo import MongoClient, InsertOne, DeleteOne, ReplaceOne, UpdateOne
# creating a MongoClient object
client = MongoClient()
# connecting with the portnumber and host
client = MongoClient("mongodb://localhost:27017/")
# accessing the database
database = client['database']
# access collection of the database
mycollection = mydatabase['myTable']
# defining the requests
requests = [InsertOne({ "x": 5}),
InsertOne({ "y": 2}),
UpdateOne({'x': 5}, {'$inc': {'x': 3}}),
DeleteOne({ "y": 2})]
# executing the requests
result = mycollection.bulk_write(requests)
for doc in mycollection.find({}):
print(doc)
Output :
{'_id': ObjectId('5f060cd7358fae75aad1ae94'), 'x': 8}

