Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Rust ドライバー
/

複数ドキュメントの検索

コレクション内の複数のドキュメントをクエリするには、 インスタンスで find() Collectionメソッドを呼び出します。

コレクション内のフィルターに一致するドキュメントを返すには、 find()メソッドにクエリフィルターを渡します。 フィルターを含めない場合、MongoDB はコレクション内のすべてのドキュメントを返します。

Tip

ドキュメントの取得の詳細については、 データの取得ガイドを参照してください。クエリフィルターの作成の詳細については、「クエリの指定」ガイドを参照してください。

find()メソッドはカーソル タイプを返します。これを反復処理して個々のドキュメントを取得できます。カーソルの使用の詳細については、「 カーソルを使用したデータへのアクセス 」ガイドを参照してください。

この例では、 sample_restaurantsデータベース内のrestaurantsコレクションからクエリフィルターに一致するドキュメントを検索します。 この例では、 Restaurant構造体のインスタンスに検索されたドキュメントのデータを入力します。

次のコードでは、 cuisineフィールドの値が"French"であるドキュメントに一致するクエリフィルターを使用します。

AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。

use mongodb::{
bson::doc,
Client,
Collection
};
use futures::TryStreamExt;
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: 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 mut cursor = my_coll.find(
doc! { "cuisine": "French" },
None
).await?;
while let Some(doc) = cursor.try_next().await? {
println!("{:?}", doc);
}
Ok(())
}
// Results truncated
...
Restaurant { name: "Cafe Un Deux Trois", cuisine: "French" }
Restaurant { name: "Calliope", cuisine: "French" }
...
use mongodb::{
bson::doc,
sync::{Client, Collection}
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: 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 mut cursor = my_coll.find(
doc! { "cuisine": "French" },
None
)?;
for result in cursor {
println!("{:?}", result?);
}
Ok(())
}
// Results truncated
...
Restaurant { name: "Cafe Un Deux Trois", cuisine: "French" }
Restaurant { name: "Calliope", cuisine: "French" }
...

戻る

1件を特定