对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
MongoDB Branding Shape
Click here >
Docs 菜单

非重复字段值

在集合中,不同文档的单个字段可能包含不同值。示例,restaurant集合中一个文档的borough 值为 "Manhattan",而另一文档的 borough 值为 "Queens"。使用Kotlin同步驱动程序,您可以检索集合中多个文档中某个字段包含的所有不同值。

本指南中的示例使用来自 Atlas 示例数据集sample_restaurants 数据库中的 restaurants 集合。要了解如何创建免费的 MongoDB 部署并加载示例数据集,请参阅 MongoDB入门指南。

以下Kotlin数据类对此集合中的文档进行建模:

data class Restaurant(
val name: String,
val borough: String,
val cuisine: String
)

要检索指定字段的非重复值,请调用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()方法提供查询筛选器,以查找集合中文档子集的不同字段值。 查询筛选器是一个表达式,指定Atlas Search用于匹配操作中的文档的条件。 有关创建查询筛选器的更多信息,请参阅指定查询。

以下示例检索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()操作的一些方法:

方法
说明

batchSize()

设置批处理返回的文档数。

collation()

指定对结果进行排序时要使用的语言排序规则类型。 有关更多信息,请参阅 MongoDB Server 手册中的排序规则

comment()

指定要附加到操作的注释。

filter()

设置要应用于查询的查询筛选器。

forEach()

distinct() 操作返回的每个元素执行给定动作。

有关可用于修改 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 文档: