You can list the distinct values of a document field in a collection by calling the distinct() method on a Collection
instance. For example, if documents in a collection contain the date
field, you can use the distinct()
method to find all the possible values for that field in the collection.
フィールド名をパラメーターとしてdistinct()
メソッドに渡すと、そのフィールドの個別の値が返されます。 また、パラメーターとしてクエリフィルターを渡し、一致したドキュメントのサブセットのみから個別のフィールド値を検索することもできます。 クエリフィルターの作成の詳細については、「 クエリの指定」ガイドを参照してください。
The distinct()
method returns the list of distinct values as a Vec<Bson>
type, a vector of Bson values.
例
この例では、 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")