List Distinct Field Values
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.
Pass a field name as a parameter to the distinct()
method to return
the distinct values for that field. You can also pass a query filter as
a parameter to find distinct field values from only a subset of matched
documents. To learn more about creating query filters, see the
Specify a Query guide.
The distinct()
method returns the list of distinct values as a Vec<Bson>
type, a vector of Bson values.
Example
This example finds distinct values for a field in the
restaurants
collection of the sample_restaurants
database.
This example finds distinct values of the borough
field in
the subset of documents in which the value of the cuisine
field
is "Turkish"
.
Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:
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(()) }
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 } }; 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(()) }
List of field values for 'borough': String("Brooklyn") String("Manhattan") String("Queens") String("Staten Island")