对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

查找文档

在本指南中,您可以了解如何使用Kotlin驱动程序通过读取操作从MongoDB集合中检索数据。您可以调用 find() 方法来检索与查询筛选条件中指定的一设立条件匹配的文档。

The examples in this guide use the movies collection in the sample_mflix database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started guide.

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

data class Movie(val title: String, val runtime: Int, val imdb: IMDB){
data class IMDB(val rating: Double)
}

以下Kotlin数据类对本指南中示例返回的结果进行建模:

data class Results(val title: String)

find() 方法从集合中检索文档。此方法采用查询筛选条件并返回所有匹配的文档。查询筛选条件是一个文档,其中指定了驱动程序用于匹配集合中的文档的条件。

如需学习;了解有关查询筛选器的更多信息,请参阅“指定查询”指南。

以下示例将 firstOrNull() 方法链接到 find() 方法调用,以查找 name字段的值为 "The Room" 的第一个文档:

val projectionFields= Projections.fields(
Projections.include(Movie::title.name, Movie::imdb.name),
Projections.excludeId()
)
val resultsFlow = collection.withDocumentClass<Results>()
.find(eq(Movie::title.name, "The Room"))
.projection(projectionFields)
.firstOrNull()
if (resultsFlow == null) {
println("No results found.");
} else {
println(resultsFlow)
}
Movie(title=The Room, runtime=99, imdb=IMDB(rating=3.7))

此示例使用 find() 方法查找其中 runtime字段的值小于 15 的所有文档。find() 操作返回一个 FindFlow对象,您可以使用 collect() 方法遍历该对象,如以下示例所示:

val projectionFields= Projections.fields(
Projections.include(Movie::title.name, Movie::imdb.name),
Projections.excludeId()
)
val resultsFlow = collection.withDocumentClass<Results>()
.find(lt(Movie::runtime.name, 15))
.projection(projectionFields)
resultsFlow.collect { println(it) }
Movie(title=Meshes of the Afternoon, runtime=14, imdb=IMDB(rating=8.0))
Movie(title=The Band Concert, runtime=9, imdb=IMDB(rating=7.9))
Movie(title=What's Opera, Doc?, runtime=7, imdb=IMDB(rating=8.3))
...

注意

查找所有文档

要查找集合中的所有文档,请将空筛选器传递给find()方法:

val resultsFlow = collection.withDocumentClass<Results>()
.find()

您可以通过将方法链接到 FindFlow实例来修改 find() 方法的行为。下表描述了修改查询的常用方法:

方法
说明

batchSize()

限制每批处理返回的文档数量。默认值为 64 个文档。

要了解批处理大小,请参阅 MongoDB Server 手册中的 cursor.batchSize()

collation()

设置查询的排序规则选项。

collect()

处理流中的每个元素并应用给定的 Lambda。

comment()

指定要添加到查询的字符串。这有助于您在服务器日志和配置数据中追踪和解释操作。

first()

返回与查询匹配的第一个文档,如果不存在匹配文档,则抛出 MongoClientException

firstOrNull()

返回与查询匹配的第一个文档,如果不存在匹配文档,则返回 null

hint()

指定用于查询的索引。

limit()

限制查询返回的文档数量。

skip()

设置要跳过的文档数。

sort()

定义要应用查询的排序条件。

以下示例链接了 limit() 方法,将查询返回的文档数量限制为 10

val projectionFields= Projections.fields(
Projections.include(Movie::title.name, Movie::imdb.name),
Projections.excludeId()
)
val resultsFlow = collection.withDocumentClass<Results>()
.find()
.projection(projectionFields)
.limit(10)

有关修改 find() 行为的方法的完整列表,请参阅Kotlin驱动程序API文档中的 FindFlow 类。

如需了解有关查询过滤器的更多信息,请参阅指定查询

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