列出不同字段值
您可以通过调用来列出集合中文档字段的唯一值distinct() 方法用于Collection
实例。例如,如果集合中的文档包含 date
字段,您可以使用 distinct()
方法查找集合中该字段的全部可能值。
将字段名称作为参数传递给 distinct()
方法,以返回该字段的唯一值。您还可以传递一个查询过滤器作为参数,以仅从匹配的文档子集中查找唯一字段值。有关创建查询过滤器的更多信息,请参阅指定查询 指南。
distinct()
方法返回唯一值的列表,以 Vec<Bson>
类型,即 Bson 值的向量。
示例
此示例在 sample_restaurants
数据库的 restaurants
集合中查找字段的唯一值。
此示例查找在 cuisine
字段值为 "Turkish"
的文档子集中 borough
字段的唯一值。
选择异步 或 同步 选项卡以查看每个运行时的对应代码
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")