批量写入
批量写入 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
方法还接受以下选项:
选项 | 说明 |
---|---|
|
|
| 如果将 |
| 该操作的写关注(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
{ update_many: { filter: { x: 1 }, update: { '$set' => { x: 2 } }, # upsert is optional and defaults to false :upsert => true, } }
replace_one
{ replace_one: { filter: { x: 1 }, replacement: { x: 2 }, # upsert is optional and defaults to false upsert: true, } }
注意
:replace_one
操作要求替换值为文档。 :replace_one
无法识别替换值中的 MongoDB 更新操作符。 在未来版本中,驱动程序预计会禁止在替换文档中使用以$
开头的键。
delete_one
{ delete_one: { filter: { x: 1 }, } }
delete_many
{ delete_many: { filter: { x: 1 }, } }
批量写入分割
驱动程序允许应用程序提交任意大的批量写入请求。 但是,由于 MongoDB Server 限制了文档的大小(当前此限制为 48 MiB),因此超过此限制的批量写入将被分割为多个请求。
使用客户端加密时,用于批量写入分割的阈值会降低,以考虑到密文的开销。