個別のフィールド値の一覧表示
コレクション内のドキュメント フィールドの個別の値を一覧表示するには、 distinct() メソッドをCollection
インスタンスのメソッドです。たとえば、コレクション内のドキュメントにdate
フィールドが含まれている場合、 distinct()
メソッドを使用して、コレクション内のそのフィールドに可能なすべての値を検索できます。
フィールド名をパラメーターとしてdistinct()
メソッドに渡すと、そのフィールドの個別の値が返されます。 また、パラメーターとしてクエリフィルターを渡し、一致したドキュメントのサブセットのみから個別のフィールド値を検索することもできます。 クエリフィルターの作成の詳細については、「 クエリの指定」ガイドを参照してください。
distinct()
メソッドは、個別の値のリストをVec<Bson>
型(BSON のベクトル)として返します。 値。
例
この例では、 sample_restaurants
データベースのrestaurants
コレクション内のフィールドの個別の値を検索します。
この例では、 cuisine
フィールドの値が"Turkish"
であるドキュメントのサブセット内で、 borough
フィールドの個別の値を検索します。
AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。
use std::env; use mongodb::{ bson::{ Document, doc }, Client, Collection }; async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; let my_coll: Collection<Document> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "cuisine": "Turkish" }; let boroughs = my_coll.distinct("borough", filter).await?; println!("List of field values for 'borough':"); for b in boroughs.iter() { println!("{:?}", b); } Ok(()) }
use std::env; use mongodb::{ bson::{ Document, doc }, sync::{ Client, Collection } }; fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; let my_coll: Collection<Document> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "cuisine": "Turkish" }; let boroughs = my_coll.distinct("borough", filter).run()?; println!("List of field values for 'borough':"); for b in boroughs.iter() { println!("{:?}", b); } Ok(()) }