批量写入
批量写入API在一次命令中向服务器发送多个写操作。使用批量写入API可以在一次写入多个数据时减少网络往返次数。例如,为了高效地执行多个更新,可以进行以下操作:
collection = client['colors'] collection.bulk_write([ { update_one: { filter: {name: 'yellow'}, update: {'$set' => {hex: 'ffff00'}}, }, }, { update_one: { filter: {name: 'purple'}, update: {'$set' => {hex: '800080'}}, }, }, ], ordered: true, write_concern: {w: :majority})
以下示例展示了如何在同一个请求中执行不同类型的操作
collection.bulk_write([ { insert_one: { x: 1 } }, { update_one: { filter: { x: 1 }, update: {'$set' => { x: 2 } }, } }, { replace_one: { filter: { x: 2 }, replacement: { x: 3 }, } }, ], :ordered => true)
函数的第一个参数是bulk_write
是要执行的操作列表。每个操作必须指定为一个包含一个键的哈希,该键是操作名称,而操作规范作为对应的值。支持的操作细节如下。bulk_write
方法还接受以下选项:
选项 | 描述 |
---|---|
bypass_document_validation | true 或 false 。是否绕过文档验证。 |
ordered | 如果将 ordered 选项设置为 true (默认值),则按顺序应用操作,如果任何操作失败,则不会尝试后续操作。如果将 ordered 选项设置为 false ,则尝试执行所有指定的操作。 |
write_concern | 操作的写关注,以哈希指定。 |
有效的批量写操作如下:
insert_one
{ insert_one: { x: 1 } }
注意
没有 insert_many
批量操作。要插入多个文档,指定多个 insert_one
操作。
update_one
{ update_one: { filter: { x: 1 }, update: { '$set' => { x: 2 } }, # upsert is optional and defaults to false upsert: true, } }
更新多个
{ update_many: { filter: { x: 1 }, update: { '$set' => { x: 2 } }, # upsert is optional and defaults to false :upsert => true, } }
替换一个
{ replace_one: { filter: { x: 1 }, replacement: { x: 2 }, # upsert is optional and defaults to false upsert: true, } }
注意
操作 :replace_one
要求替换值是一个文档。在替换值中,:replace_one
不会识别 MongoDB 更新操作符。在未来的版本中,驱动器预计将禁止在替换文档中使用以 $
开头的键。
删除一个
{ delete_one: { filter: { x: 1 }, } }
删除多个
{ delete_many: { filter: { x: 1 }, } }
批量写入拆分
驱动程序允许应用程序提交任意大小的批量写入请求。然而,由于MongoDB服务器限制了命令文档的大小(目前这个限制是48 MiB),超过这个限制的批量写入将被拆分为多个请求。
当客户端加密被使用时,用于批量写入拆分的阈值降低,以允许密文的开销。