列出不同字段值
您可以通过在 实例上调用 distinct() Collection
方法来列出集合中文档字段的非重复值。示例,如果集合中的文档包含 date
字段,则可以使用 distinct()
方法在集合中查找该字段的所有可能值。
将字段名称作为参数传递给distinct()
方法,以返回该字段的非重复值。 您还可以将查询过滤作为参数传递,以仅从匹配文档的子集中查找不同的字段值。 要学习;了解有关创建查询筛选器的更多信息,请参阅指定查询指南。
distinct()
方法以 类型返回不同值的列表,该类型是Vec<Bson>
BSON向量 值。
例子
此示例查找 sample_restaurants
数据库的 restaurants
集合中某个字段的不同值。 distinct()
方法检索 cuisine
字段值为 "Turkish"
的文档子集中 borough
字段的不同值。
您可以将 restaurants
集合中的文档作为 Document
类型或自定义数据类型的实例访问权限。 要指定哪种数据类型表示集合的数据,请将突出显示的行上的 <T>
类型参数替换为以下值之一:
<Document>
:将集合文档表示为BSON文档<Restaurant>
:将集合文档表示为Restaurant
结构的实例,该结构在代码顶部定义
选择 Asynchronous或Synchronous标签页,查看每个运行时的相应代码:
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")