您可以通过在 Collection 实例上调用 insert_one() 方法,将文档插入到集合中。
您必须插入与参数化Collection实例相同类型的文档。 示例,如果使用MyStruct结构对集合进行参数化,请将MyStruct实例作为参数传递给insert_one()方法以插入文档。 要学习;了解有关指定类型参数的更多信息,请参阅数据库和集合指南中的集合参数化部分。
insert_one() 方法返回InsertOneResult 类型,其中包含新插入文档的 _id字段。
要了解有关insert_one()方法的更多信息,请参阅“插入文档”指南。
例子
restaurantssample_restaurants此示例将文档插入数据库的collection集合中。该示例使用具有name 、 borough和cuisine字段的Restaurant结构体来对collection中的文档进行建模。
以下代码创建一个Restaurant实例并将其插入到collection中。
选择 Asynchronous或Synchronous标签页,查看每个运行时的相应代码:
use std::env; use mongodb::{ bson::doc, 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?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let doc = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; let res = my_coll.insert_one(doc, None).await?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }
Inserted a document with _id: ObjectId("...")
use std::env; use mongodb::{ bson::doc, 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)?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let doc = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; let res = my_coll.insert_one(doc, None)?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }
Inserted a document with _id: ObjectId("...")