Overview
在本指南中,您可以了解如何将文档插入到 MongoDB 集合。
在 MongoDB 中查找、更新和删除任何文档之前,您需要先插入文档。 您可以使用以下方法插入文档:
insert_one()插入一个文档insert_many()插入一个或多个文档
本指南包括以下部分:
_id 字段
在 MongoDB collection中,每个文档都必须包含唯一的_id字段值。当您将数据插入collection时,驱动程序会自动为每个文档生成一个唯一值作为ObjectId类型。
如果您希望设置自定义值,则可以在传递给插入操作的文档的_id字段中分配这些值。
重要
重复 _id 值
如果尝试插入包含重复的_id值的文档,这些值会违反唯一索引约束并导致写入操作失败。
插入文档
使用 insert_one() 方法向集合插入多个文档。
您必须插入与参数化Collection实例相同类型的文档。 例如,如果使用MyStruct MyStruct结构对collection进行了参数化,请将instance作为参数传递给insert_one() 方法以插入文档。要了解有关指定类型参数的更多信息,请参阅数据库和collection指南中的collection参数化部分。
插入成功后,该方法将返回一个 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).await?; println!("Inserted document with _id: {}", insert_one_result.inserted_id);
Inserted document with _id: 8
提示
不存在的数据库和集合
如果对数据库和collection执行写入操作时不存在,服务器会自动创建它们。
修改 insert_one 行为
您可以通过将选项构建器方法链接到insert_one()来修改insert_one()方法的行为。 这些选项构建器方法设立InsertOneOptions结构体字段。
注意
设置选项
您可以通过将选项构建器方法直接链接到 insert_one() 方法调用来设立InsertOneOptions 字段。如果使用的是早期版本的驱动程序,则必须通过将选项构建器方法链接到 builder() 方法来构造 InsertOneOptions实例。然后,将选项实例作为参数传递给 insert_one()。
下表描述了InsertOneOptions中可用的选项:
选项 | 说明 |
|---|---|
| |
| |
|
|
以下代码展示了如何通过将bypass_document_validation()方法链接到insert_one()方法来设立bypass_document_validation字段:
let _result = my_coll.insert_one(doc) .bypass_document_validation(true) .await?;
完整文件示例:插入一个文档
此示例将文档插入到 sample_restaurants数据库的 restaurants集合中。 insert_one() 方法插入具有 name、borough 和 cuisine字段值的文档。
您可以将此文档作为 Document 类型或自定义数据类型的实例插入。 要指定代表集合数据的数据类型,请对突出显示的行执行以下操作:
要访问权限集合文档并将其作为BSON文档插入,请将
<T>类型参数替换为<Document>,并将<struct or doc>占位符替换为insert_doc。要访问权限集合文档并将其作为
Restaurant结构体的实例插入,请将<T>类型参数替换为<Restaurant>,并将<struct or doc>占位符替换为insert_struct。Restaurant结构体在代码文件的顶部定义。
选择Asynchronous或Synchronous标签页,查看每个运行时的相应代码:
use std::env; use mongodb::{ bson::{doc, Document}, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_doc = doc! { "name": "Sea Stone Tavern", "cuisine": "Greek", "borough": "Queens", }; let insert_struct = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; // Replace <struct or doc> with the insert_struct or insert_doc variable let res = my_coll.insert_one(<struct or doc>).await?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }
Inserted a document with _id: ObjectId("...")
use std::env; use mongodb::{ bson::{doc, Document}, sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_doc = doc! { "name": "Sea Stone Tavern", "cuisine": "Greek", "borough": "Queens", }; let insert_struct = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; // Replace <struct or doc> with the insert_struct or insert_doc variable let res = my_coll.insert_one(<struct or doc>).run()?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }
Inserted a document with _id: ObjectId("...")
插入多个文档
使用 insert_many() 方法向集合插入多个文档。
将包含一个或多个文档的向量传递给insert_many()方法,以将它们插入到collection中。这些文档必须是您参数化Collection实例时使用的类型的实例。 例如,如果使用 结构对collection进行了参数化,请将实例向量作为参数传递给MyStruct MyStructinsert_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).await?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{:?}", value); }
Inserted documents with _ids: Int32(5) Int32(6) Int32(7)
提示
不存在的数据库和集合
如果对数据库和collection执行写入操作时不存在,服务器会自动创建它们。
修改 insert_many 行为
您可以通过将选项构建器方法链接到insert_many()来修改insert_many()方法的行为。 这些选项构建器方法设立InsertManyOptions结构体字段。
下表描述了InsertManyOptions中可用的选项:
选项 | 说明 |
|---|---|
| |
| 如果为 |
| |
|
|
以下代码展示了如何通过将comment()方法链接到insert_many()方法来设立comment字段:
let _result = my_coll.insert_many(docs) .comment(Some("hello world".into())) .await?;
完整文件示例:插入多个文档
此示例将多个文档插入到 sample_restaurants数据库的 restaurants集合中。 该示例通过将文档向量传递给 insert_many() 方法来插入具有 name 和 cuisine字段值的文档。
您可以将这些文档作为 Document 类型或自定义数据类型的实例插入。 要指定代表集合数据的数据类型,请对突出显示的行执行以下操作:
要访问权限集合文档并将其作为BSON文档插入,请将
<T>类型参数替换为<Document>,并将<struct or doc>占位符替换为insert_docs。要访问权限集合文档并将其作为
Restaurant结构体的实例插入,请将<T>类型参数替换为<Restaurant>,并将<struct or doc>占位符替换为insert_structs。Restaurant结构体在代码文件的顶部定义。
选择Asynchronous或Synchronous标签页,查看每个运行时的相应代码:
use mongodb::{ bson::{doc, Document}, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_docs = vec! [ doc! { "name": "While in Kathmandu", "cuisine": "Nepalese", }, doc! { "name": "Cafe Himalaya", "cuisine": "Nepalese", } ]; let insert_structs = vec! [ Restaurant { name: "While in Kathmandu".to_string(), cuisine: "Nepalese".to_string(), }, Restaurant { name: "Cafe Himalaya".to_string(), cuisine: "Nepalese".to_string(), } ]; // Replace <structs or docs> with the insert_structs or insert_docs variable let insert_many_result = my_coll.insert_many(<structs or docs>).await?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{}", value); } Ok(()) }
Inserted documents with _ids: ObjectId("...") ObjectId("...")
use mongodb::{ bson::{doc, Document}, sync::{Client, Collection} }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_docs = vec! [ doc! { "name": "While in Kathmandu", "cuisine": "Nepalese", }, doc! { "name": "Cafe Himalaya", "cuisine": "Nepalese", } ]; let insert_structs = vec! [ Restaurant { name: "While in Kathmandu".to_string(), cuisine: "Nepalese".to_string(), }, Restaurant { name: "Cafe Himalaya".to_string(), cuisine: "Nepalese".to_string(), } ]; // Replace <structs or docs> with the insert_structs or insert_docs variable let insert_many_result = my_coll.insert_many(<structs or docs>).run()?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{}", value); } Ok(()) }
Inserted documents with _ids: ObjectId("...") ObjectId("...")
有序行为示例
假设您要将以下文档插入到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" }
当您尝试插入这些文档时,结果取决于传递给ordered()选项构建器方法的值:
如果传递的值为
true(默认值),则驱动程序在尝试插入具有重复_id值的文档时会抛出BulkWriteError。但是,驱动程序仍会在错误发生之前插入文档。如果您传递
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: 1, title: "Blueberries for Sal".to_string(), author: "".to_string() }, Book { _id: 3, title: "Goodnight Moon".to_string(), author: "".to_string() } ]; my_coll.insert_many(docs).ordered(false).await?;
即使此操作的结果是BulkWriteError ,您仍然可以在collection中找到未出错的文档:
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" } { "_id": 3, "title": "Goodnight Moon" }
更多信息
有关插入操作的可运行示例,请参阅以下使用示例:
API 文档
要进一步了解本指南所提及的方法和类型,请参阅以下 API 文档: