Docs 菜单
Docs 主页
/ / /
Ruby MongoDB 驱动程序
/

批量写入

在此页面上

  • insert_one
  • update_one
  • update_many
  • replace_one
  • delete_one
  • delete_many
  • 批量写入分割

批量写入 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
truefalse 。是否绕过文档验证。
ordered
如果将ordered选项设置为true (默认值),则按顺序应用操作,如果任何操作失败,则不会尝试后续操作。 如果将ordered选项设置为false ,则会尝试所有指定的操作。
write_concern
该操作的写关注(write concern),指定为哈希值。

有效的批量写入操作如下:

{ insert_one: { x: 1 } }

注意

没有insert_many批量操作。 要插入多个文档,请指定多个insert_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 Server 限制了文档的大小(当前此限制为 48 MiB),因此超过此限制的批量写入将被分割为多个请求。

使用客户端加密时,用于批量写入分割的阈值会降低,以考虑到密文的开销。

后退

增删改查操作

来年

投射