Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Rust 驱动程序
/

插入文档

您可以通过在 实例上调用 insert_one() Collection方法,将文档插入到集合中。

您必须插入与参数化Collection实例相同类型的文档。 示例,如果使用MyStruct结构对集合进行参数化,请将MyStruct实例作为参数传递给insert_one()方法以插入文档。 要学习;了解有关指定类型参数的更多信息,请参阅数据库和集合指南中的集合参数化部分。

insert_one()方法返回 InsertOneResult _id包含新插入文档的 字段的类型。

要了解有关insert_one()方法的更多信息,请参阅“插入文档”指南。

restaurantssample_restaurants此示例将文档插入数据库的collection集合中。该示例使用具有nameboroughcuisine字段的Restaurant结构体来对collection中的文档进行建模。

以下代码创建一个Restaurant实例并将其插入到collection中。

选择 AsynchronousSynchronous标签页,查看每个运行时的相应代码:

use std::env;
use mongodb::{ bson::doc, Client, Collection };
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
borough: String,
cuisine: String,
name: String,
}
#[tokio::main]
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 };
#[derive(Serialize, Deserialize, Debug)]
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("...")

后退

查找多个