個別のフィールド値の一覧表示
インスタンスで distinct() メソッドを呼び出すと、コレクション内のドキュメントフィールドの個別の値を一覧表示できます。Collection
例、コレクション内のドキュメントに date
フィールドが含まれている場合、distinct()
メソッドを使用して、コレクション内のそのフィールドに可能なすべての値を検索できます。
フィールド名をパラメーターとしてdistinct()
メソッドに渡すと、そのフィールドの個別の値が返されます。 また、パラメーターとしてクエリフィルターを渡し、一致したドキュメントのサブセットのみから個別のフィールド値を検索することもできます。 クエリフィルターの作成の詳細については、「 クエリの指定」ガイドを参照してください。
distinct()
メソッドは、個別の値のリストをVec<Bson>
型(BSON のベクトル)として返します。 値。
例
この例では、 sample_restaurants
データベースの restaurants
コレクション内のフィールドの個別の値を検索します。 distinct()
メソッドは、cuisine
フィールドの値が "Turkish"
であるドキュメントのサブセット内の borough
フィールドの個別の値を検索します。
restaurants
コレクション内のドキュメントには、Document
型またはカスタムデータ型のインスタンスとしてアクセスできます。 コレクションのデータを表すデータ型を指定するには、強調表示された行の <T>
型パラメータを次のいずれかの値に置き換えます。
<Document>
:コレクションドキュメントをBSONドキュメントとして表現します<Restaurant>
: コードの上部で定義されたRestaurant
構造体のインスタンスとしてコレクションドキュメントを表します
AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。
use std::env; use mongodb::{ bson::{ Document, doc }, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, borough: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = 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(()) }
List of field values for 'borough': String("Brooklyn") String("Manhattan") String("Queens") String("Staten Island")
use std::env; use mongodb::{ bson::{ Document, doc }, sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, borough: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = 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(()) }
List of field values for 'borough': String("Brooklyn") String("Manhattan") String("Queens") String("Staten Island")