您可以通过在 实例上调用 insert_one() Collection
方法,将文档插入到集合中。
您必须插入与参数化Collection
实例相同类型的文档。 示例,如果使用MyStruct
结构对集合进行参数化,请将MyStruct
实例作为参数传递给insert_one()
方法以插入文档。 要学习;了解有关指定类型参数的更多信息,请参阅数据库和集合指南中的集合参数化部分。
insert_one()
方法返回 InsertOneResult _id
包含新插入文档的 字段的类型。
要了解有关insert_one()
方法的更多信息,请参阅“插入文档”指南。
例子
restaurants
sample_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).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).run()?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }
Inserted a document with _id: ObjectId("...")