连接到 MongoDB
1
创建您的 Rust 应用程序
打开名为main.rs
的文件,位于您的 rust_quickstart/src
项目目录中。在这个文件中,您可以开始编写您的应用程序。
将以下代码复制并粘贴到 main.rs
文件中
use mongodb::{ bson::{Document, doc}, Client, Collection }; async fn main() -> mongodb::error::Result<()> { // Replace the placeholder with your Atlas connection string let uri = "<connection string>"; // Create a new client and connect to the server let client = Client::with_uri_str(uri).await?; // Get a handle on the movies collection let database = client.database("sample_mflix"); let my_coll: Collection<Document> = database.collection("movies"); // Find a movie based on the title value let my_movie = my_coll.find_one(doc! { "title": "The Perils of Pauline" }).await?; // Print the document println!("Found a movie:\n{:#?}", my_movie); Ok(()) }
use mongodb::{ bson::{Document, doc}, sync::{Client, Collection} }; fn main() -> mongodb::error::Result<()> { // Replace the placeholder with your Atlas connection string let uri = "<connection string>"; // Create a new client and connect to the server let client = Client::with_uri_str(uri)?; // Get a handle on the movies collection let database = client.database("sample_mflix"); let my_coll: Collection<Document> = database.collection("movies"); // Find a movie based on the title value let my_movie = my_coll .find_one(doc! { "title": "The Perils of Pauline" }) .run()?; // Print the document println!("Found a movie:\n{:#?}", my_movie); Ok(()) }
2
分配连接字符串
将代码块中的 <connection string>
占位符替换为您从创建连接字符串 步骤中复制的连接字符串。
3
运行您的Rust应用程序
在您的shell中,运行以下命令以编译并运行此应用程序
cargo run
命令行输出包含检索到的电影文档的详细信息
Found a movie: Some( Document({ "_id": ObjectId(...), "title": String( "The Perils of Pauline", ), "plot": String( "Young Pauline is left a lot of money ...", ), "runtime": Int32( 199, ), "cast": Array([ String( "Pearl White", ), String( "Crane Wilbur", ), ... ]), }), )
如果遇到错误或没有输出,请确保您在 main.rs
文件中指定了正确的连接字符串,并且您已加载示例数据。
完成这些步骤后,您将拥有一个工作中的应用程序,该应用程序使用驱动程序连接到您的MongoDB部署,对示例数据进行查询,并打印出结果。
注意
如果您在这一步骤中遇到问题,请在MongoDB社区论坛 中寻求帮助或通过使用此页面上方的反馈 按钮提交反馈。