插入文档
您可以通过在 实例上调用 insert_one() Collection
方法,将文档插入到集合中。
您必须插入与参数化Collection
实例相同类型的文档。 示例,如果使用MyStruct
结构对集合进行参数化,请将MyStruct
实例作为参数传递给insert_one()
方法以插入文档。 要学习;了解有关指定类型参数的更多信息,请参阅数据库和集合指南中的集合参数化部分。
insert_one()
方法返回 InsertOneResult _id
包含新插入文档的 字段的类型。
要了解有关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
结构体在代码文件的顶部定义。
选择 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("...")