Docs 菜单
Docs 主页
/ / /
Rust 驱动程序
/ / /

插入文档

在此页面上

  • 概述
  • _id 字段
  • 插入文档
  • 例子
  • 修改 insert_one 行为
  • 插入多个文档
  • 例子
  • 修改 insert_many 行为
  • 有序行为示例
  • 更多信息
  • API 文档

在本指南中,您可以了解如何将文档插入到 MongoDB 集合。

在 MongoDB 中查找、更新和删除任何文档之前,您需要先插入文档。 您可以使用以下方法插入文档:

  • insert_one() 插入一个文档

  • insert_many() 插入一个或多个文档

本指南包括以下部分:

  • _id 字段描述每个文档包含的_id字段

  • 插入文档描述了如何使用驱动程序将单个文档插入到集合中

  • 插入多个文档描述了如何使用驱动程序将多个文档插入到集合中

  • 其他信息提供了指向本指南中提及的类型和方法的资源和 API 文档的链接

在 MongoDB collection中,每个文档都必须包含唯一的_id字段值。当您将数据插入collection时,驱动程序会自动为每个文档生成一个唯一值作为ObjectId类型。

如果您希望设置自定义值,则可以在传递给插入操作的文档的_id字段中分配这些值。

重要

重复 _id 值

如果尝试插入包含重复的_id值的文档,这些值会违反唯一索引约束并导致写入操作失败。

要了解有关_id 字段的更多信息,请参阅 MongoDB Server手册中的 唯一索引 。

要了解有关文档结构和规则的更多信息,请参阅 MongoDB Server手册中的 文档 。

使用 insert_one() 方法向集合插入多个文档。

插入成功后,该方法会返回一个实例,其中包含所插入文档的InsertOneResult _id

以下示例使用insert_one() books方法将文档插入collection集合:

let my_coll: Collection<Book> = client.database("db").collection("books");
let doc = Book { _id: 8, title: "Atonement".to_string(), author: "Ian McEwan".to_string() };
let insert_one_result = my_coll.insert_one(doc, None).await?;
println!("Inserted document with _id: {}", insert_one_result.inserted_id);

提示

不存在的数据库和集合

如果对数据库和collection执行写入操作时不存在,服务器会自动创建它们。

您可以通过构造和传递InsertOneOptions结构体来修改insert_one()方法的行为。

注意

实例化选项

Rust 驱动程序实现了用于创建许多不同类型的 Builder 设计模式,包括InsertOneOptions 。 您可以使用每种类型的builder()方法,通过逐个链接选项构建器函数来构造选项实例。

下表描述了InsertOneOptions中可用的选项:

选项
说明
bypass_document_validation
如果true ,则允许驱动程序执行违反文档级验证的写入。要了解有关验证的更多信息,请参阅模式验证指南。

类型: bool
默认: false
write_concern
该操作的写关注。 如果不设置此选项,该操作将继承为集合设置的写关注。 要了解有关写关注的更多信息,请参阅 MongoDB Server手册中的 写关注 。

类型: WriteConcern
comment
与操作绑定的任意Bson值,以通过数据库分析器、 currentOp和日志进行跟踪。 此选项仅在连接到 MongoDB Server 4.4 及更高版本时可用。

类型: Bson
默认: None

以下代码展示了如何构造InsertOneOptions实例:

let _opts = InsertOneOptions::builder()
.bypass_document_validation(true)
.build();

使用 insert_many() 方法向集合插入多个文档。

插入成功后,该方法会返回一个实例,其中包含所插入文档的InsertManyResult _id值。

以下示例使用insert_many()方法将多个文档插入到bookscollection中:

let docs = vec![
Book {
_id: 5,
title: "Cat's Cradle".to_string(),
author: "Kurt Vonnegut Jr.".to_string()
},
Book {
_id: 6,
title: "In Memory of Memory".to_string(),
author: "Maria Stepanova".to_string()
},
Book {
_id: 7,
title: "Pride and Prejudice".to_string(),
author: "Jane Austen".to_string()
}
];
let insert_many_result = my_coll.insert_many(docs, None).await?;
println!("Inserted documents with _ids:");
for (_key, value) in &insert_many_result.inserted_ids {
println!("{:?}", value);
}

提示

不存在的数据库和集合

如果对数据库和collection执行写入操作时不存在,服务器会自动创建它们。

您可以通过构造和传递InsertManyOptions结构体来修改insert_many()方法的行为。 下表描述了InsertManyOptions中可用的选项:

选项
说明
bypass_document_validation
如果true ,则允许驱动程序执行违反文档级验证的写入。要了解有关验证的更多信息,请参阅模式验证指南。

类型: bool
默认: false
ordered
如果true ,则当任何插入失败时,操作都会返回而不插入剩余文档。 如果为false ,即使插入失败,操作也会继续执行剩余的写入操作。 要了解有关有序插入的更多信息,请参阅本指南的有序行为示例部分。

类型: bool
默认: true
write_concern
该操作的写关注。 如果不设置此选项,该操作将继承为集合设置的写关注。 要了解有关写关注的更多信息,请参阅 MongoDB Server手册中的 写关注 。

类型: WriteConcern
comment
与操作绑定的任意Bson值,以通过数据库分析器、 currentOp和日志进行跟踪。 此选项仅在连接到 MongoDB Server 4.4 及更高版本时可用。

类型: Bson
默认: None

以下代码展示了如何构造InsertManyOptions实例:

let _opts = InsertManyOptions::builder()
.comment(Some("hello world".into()))
.build();

假设您要将以下文档插入到bookscollection中:

{ "_id": 1, "title": "Where the Wild Things Are" }
{ "_id": 2, "title": "The Very Hungry Caterpillar" }
{ "_id": 1, "title": "Blueberries for Sal" }
{ "_id": 3, "title": "Goodnight Moon" }

当您尝试插入这些文档时,结果取决于InsertManyOptionsordered选项的值:

  • 如果 orderedtrue(默认值),则当尝试插入具有重复 _id 值的文档时,驱动程序会抛出 BulkWriteError。但是,驱动程序仍会在错误发生之前插入文档。

  • 如果将ordered设置为false ,则驱动程序在尝试插入具有重复_id值的文档时仍会抛出BulkWriteError ,但会插入所有其他文档。

以下代码演示如何执行无序写入操作以插入前面的文档:

let docs = vec![
Book { _id: 1, title: "Where the Wild Things Are".to_string(), author: "".to_string() },
Book { _id: 2, title: "The Very Hungry Caterpillar".to_string(), author: "".to_string() },
Book { _id: 4, title: "Blueberries for Sal".to_string(), author: "".to_string() },
Book { _id: 3, title: "Goodnight Moon".to_string(), author: "".to_string() }
];
let opts = InsertManyOptions::builder().ordered(false).build();
my_coll.insert_many(docs, opts).await?;

即使此操作的结果是BulkWriteError ,您仍然可以在collection中找到未出错的文档:

{ "_id": 1, "title": "Where the Wild Things Are" }
{ "_id": 2, "title": "The Very Hungry Caterpillar" }
{ "_id": 3, "title": "Goodnight Moon" }

有关插入操作的可运行示例,请参阅以下使用示例:

要进一步了解本指南所提及的方法和类型,请参阅以下 API 文档:

← 写入操作