Overview
在集合中,不同文档的单个字段可能包含不同值。示例,restaurant集合中一个文档的borough 值为 "Manhattan",而另一文档的 borough 值为 "Queens"。使用Kotlin同步驱动程序,您可以检索集合中多个文档中某个字段包含的所有不同值。
样本数据
本指南中的示例使用 Atlas示例数据集的sample_restaurants数据库中的restaurants集合。 要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。
以下Kotlin数据类对此集合中的文档进行建模:
data class Restaurant(     val name: String,     val borough: String,     val cuisine: String ) 
distinct() 方法
要检索指定字段的非重复值,请调用distinct()方法并传入要查找非重复值的字段的名称。
检索集合中的不同值
以下示例检索restaurants集合中borough字段的非重复值:
val results = collection.distinct<String>(Restaurant::borough.name) results.forEach { result ->     println(result) } 
Bronx Brooklyn Manhattan Missing Queens Staten Island 
结果显示集合中所有文档的borough字段中出现的每个不同值。 尽管多个文档在borough字段中具有相同的值,但每个值仅在结果中出现一次。
检索指定文档中的不同值
您可以为distinct()方法提供查询过滤,以查找集合中文档子集合的不同字段值。 查询过滤是一个表达式,用于指定在操作中匹配文档的搜索条件。 有关创建查询过滤的更多信息,请参阅指定查询。
以下示例检索cuisine字段值为"Italian"的所有文档的borough字段的非重复值:
val results = collection.distinct<String>(     Restaurant::borough.name,     eq(Restaurant::cuisine.name, "Italian") ) results.forEach { result ->     println(result) } 
Bronx Brooklyn Manhattan Queens Staten Island 
修改不同行为
可以通过将方法链接到 distinct() 方法调用来修改 distinct() 方法。如果不指定任何选项,驱动程序不会自定义操作。
下表描述了可用于自定义distinct()操作的一些方法:
| 方法 | 说明 | 
|---|---|
| 
 | Sets the number of documents to return per batch. | 
| 
 | Specifies the kind of language collation to use when sorting
results. For more information, see Collation
in the MongoDB Server manual. | 
| 
 | Specifies a comment to attach to the operation. | 
| 
 | Sets the query filter to apply to the query. | 
| 
 | Performs the given action on each element returned by the  distinct()operation. | 
有关可用于修改 distinct() 方法的方法的完整列表,请参阅 DistinctIterable API文档。
以下示例检索borough字段值为"Bronx"且cuisine字段值为"Pizza"的所有文档的name字段的非重复值。 它还使用comment选项为操作添加注释。
val results = collection.distinct<String>(     Restaurant::name.name,     and(         eq(Restaurant::borough.name, "Bronx"),         eq(Restaurant::cuisine.name, "Pizza")     ) ).comment("Bronx pizza restaurants") results.forEach { result ->     println(result) } 
$1.25 Pizza 18 East Gunhill Pizza 2 Bros Aenos Pizza Alitalia Pizza Restaurant ... 
更多信息
要学习;了解有关 distinct 命令的更多信息,请参阅MongoDB Server手册中的Distinct指南。
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: