MongoDB.local SF, Jan 15: See the speaker lineup & ship your AI vision faster. Use WEB50 to save 50%
Find out more >
Docs 菜单
Docs 主页
/ /
从 MongoDB 读取数据

Retrieve Data

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

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

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

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

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

以下示例使用find()方法查找cuisine字段的值为"Spanish"的所有文档:

val results = collection.find(eq(Restaurant::cuisine.name, "Spanish"))

上示例中的find()操作会返回一个FindIterable对象,您可以使用forEach()方法遍历该对象,如以下示例所示:

val results = collection.find(eq(Restaurant::cuisine.name, "Spanish"))
results.forEach { result ->
println(result)
}
Restaurant(name=Tropicoso Club, cuisine=Spanish)
Restaurant(name=Beso, cuisine=Spanish)
Restaurant(name=Sabor Latino Restaurant, cuisine=Spanish)
...

注意

查找所有文档

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

val results = collection.find()

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

方法
说明

batchSize()

Limits the number of documents to return per batch. To learn more about batch size, see cursor.batchSize() in the MongoDB Server manual.

collation()

Sets the collation options for the query.

comment()

Specifies a string to attach to the query. This can help you trace and interpret the operation in the server logs and in profile data. To learn more about query comments, see $comment in the MongoDB Server manual.

hint()

Specifies the index to use for the query.

limit()

Limits the number of documents to be returned from the query.

maxTime()

Sets the maximum execution time on the server for this operation.

skip()

Sets the number of documents to skip.

sort()

Defines the sort criteria to apply to the query.

以下示例链接了limit()maxTime()方法,以将查询返回的文档数限制为10 ,设立操作的最长执行时间设置为10000毫秒:

val results = collection
.find(eq(Restaurant::cuisine.name, "Spanish"))
.limit(10)
.maxTime(10000)

有关修改find() 行为的方法的完整列表,请参阅 类的API文档 FindIterable

要查看使用Kotlin Sync驱动程序检索文档的可运行代码示例,请参阅 从MongoDB读取数据。

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

  • find()

  • FindIterable

后退

指定查询

在此页面上