Docs 菜单
Docs 主页
/ / /
Kotlin Sync 驱动程序
/

检索不同字段值

在此页面上

  • Overview
  • 样本数据
  • distinct() 方法
  • 检索集合中的不同值
  • 检索指定文档中的不同值
  • 修改不同行为
  • 更多信息
  • API 文档

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

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

以下 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)
}

结果显示集合中所有文档的borough字段中出现的每个不同值。 尽管多个文档在borough字段中具有相同的值,但每个值仅在结果中出现一次。

您可以为distinct()方法提供查询筛选器,以查找集合中文档子集的不同字段值。查询筛选器是一个表达式,用于指定在操作中匹配文档的搜索条件。有关创建查询筛选器的更多信息,请参阅指定查询。

以下示例检索cuisine字段值为"Italian"的所有文档的borough字段的非重复值:

val results = collection.distinct<String>(
Restaurant::borough.name,
eq(Restaurant::cuisine.name, "Italian")
)
results.forEach { result ->
println(result)
}

可以通过将方法链接到distinct()方法调用来修改distinct()方法。如果不指定任何选项,驱动程序不会自定义操作。

下表描述了可用于自定义distinct()操作的一些方法:

方法
说明
batchSize()
Sets the number of documents to return per batch.
collation()
Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.
comment()
Specifies a comment to attach to the operation.
filter()
Sets the query filter to apply to the query.
forEach()
Performs the given action on each element returned by the distinct() operation.
maxTime()
Sets the maximum amount of time to allow the operation to run, in milliseconds.

有关可用于修改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)
}

要了解有关 distinct 命令的更多信息,请参阅 MongoDB Server 手册中的Distinct 指南

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

  • distinct()

  • DistinctIterable

后退

计算文档