📜  Python MongoDB – bulk_write()(1)

📅  最后修改于: 2023-12-03 15:04:06.258000             🧑  作者: Mango

Python MongoDB – bulk_write()

Python MongoDB driver provides a method to perform bulk operations. bulk_write() method in PyMongo is used to perform multiple operations like insert, update, delete in bulk. This method can improve the performance of the application as the number of roundtrips to the server is reduced.

Syntax
bulk_write(requests, ordered=True, bypass_document_validation=False, session=None)
  • requests: A list of write operations to be executed as a BulkWriteOperation. Each request is represented as a dictionary.
  • ordered: If set to True(default value), the mongodb executes the operations in order. Set it to False to execute the operations in parallel.
  • bypass_document_validation: If set to True, PyMongo will not validate the documents before sending them to mongodb server.
  • session: An optional client session object that can be used to execute the operation in a transaction.
Example

Let's take an example of bulk_write() method by performing multiple insert operations in a single database trip:

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

client = MongoClient()
collection = client.mydb.mycollection

# Create requests list for bulk write operation
requests = [
    InsertOne({"name": "john", "age": 25}),
    InsertOne({"name": "jane", "age": 30})
]

# Execute bulk write operation
result = collection.bulk_write(requests)

# Print the number of inserted documents
print(result.inserted_count)

The above script creates a collection and performs two insert operations using bulk_write() method.

Conclusion

bulk_write() method in PyMongo is a powerful method to perform multiple database operations in a single trip. By reducing the number of roundtrips to the server, it can improve the performance of your application.