插入文档
您可以通过调用insert_one() 方法在Collection
实例上。
你必须插入与您参数化 Collection
实例时相同的类型的文档。例如,如果您使用 MyStruct
结构体参数化了集合,请将 MyStruct
实例作为参数传递给 insert_one()
方法以插入文档。有关指定类型参数的更多信息,请参阅集合参数化 部分的数据库和集合指南。
insert_one()
方法返回一个包含新插入文档的 _id
字段的 InsertOneResult 类型。
有关 insert_one()
方法的更多信息,请参阅 插入文档 指南。
示例
本例将文档插入到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
结构。
选择异步或同步选项卡以查看每个运行时对应的代码
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("...")