对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

插入文档

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

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

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, 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 };
#[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, None)?;
println!("Inserted a document with _id: {}", res.inserted_id);
Ok(())
}
Inserted a document with _id: ObjectId("...")