AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

MongoDB に接続する

1

rust_quickstart/srcプロジェクトディレクトリ内の main.rs というファイルを開きます。このファイルで、アプリケーションの記述を開始できます。

以下のコードをコピーして、main.rs ファイルに貼り付けます。

use mongodb::{ bson::{Document, doc}, Client, Collection }; #[tokio::main]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" }, None).await?; // Print the document println!("Found a movie:\n{:#?}", my_movie); Ok(())}
2

<connection string> プレースホルダーを、このガイドの「接続文字列の作成」ステップからコピーした接続文字列に置き換えます。

3

このアプリケーションをコンパイルして実行するには、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 ファイルに適切な接続stringが指定されており、サンプル データがロードされていることを確認してください。

これらの手順を完了すると、ドライバーを使用して MongoDB 配置に接続し、サンプル データに対してクエリを実行し、結果を出力する動作するアプリケーションが作成されます。

注意

この手順で問題が発生した場合は、 MongoDB Stack Overflowタグ または 一般的な技術サポートのためのMongoDB Reddit Community を参照してください。また、 接続トラブルシューティングガイドを参照してください。

このページを評価