Python MongoDB – bulk_write()
MongoDB 是一个开源的面向文档的数据库。 MongoDB以键值对的形式存储数据,是一个NoSQL数据库程序。 NoSQL 一词的意思是非关系型的。有关 MongoDB 的更详细介绍,请参阅 MongoDB: An Introduction。现在让我们使用Python来了解 MongoDB 中的 Bulk Write 操作。
批量写入()
PyMongo函数bulk_write()
向服务器发送一批写操作。批量执行写入操作会增加写入吞吐量。
Syntax : bulk_write(requests, ordered = True, bypass_document_validation = False, session = None)
Parameters :
- 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.
示例 1:使用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)
在这里,前两个文档是使用InsertOne 命令插入的。然后使用DeleteOne命令删除具有Student 名称的文档: Cody 。使用ReplaceOne命令,名称为Drew的学生将替换为名称Andrew。因此,所有这些命令都按顺序执行,我们得到以下输出:
输出 :
{‘_id’: ObjectId(‘5f060aa5a9666ecd86f5b6bd’), ‘Student name’: ‘Andrew’}
示例 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)
这里首先使用InsertOne命令插入两个文档。然后更新x 值为 5的文档,并将其值增加 3。最后,使用命令DeleteOne删除包含y的文档。
输出 :
{'_id': ObjectId('5f060cd7358fae75aad1ae94'), 'x': 8}