文档菜单
文档首页
/ / /
Kotlin 协程

跳过返回结果

在本页中

  • 概述
  • 示例
  • 使用 FindIterable
  • 使用聚合

在本指南中,您可以学习如何使用MongoDB Kotlin驱动程序从读取操作中跳过指定数量的返回结果。

您可以通过使用skip() 方法在查询的返回结果上跳过结果。您还可以通过指定 $skip 聚合阶段来跳过聚合管道中特定阶段的文档。

skip() 方法接受一个整数,指定要跳过由 FindFlow 返回的文档列表开头的文档数量。FindFlow.

您可以使用 skip() 方法跳过前两个文档,如下所示

collection.find().skip(2)

Aggregates.skip() 是聚合管道中的一个可选阶段,指定要从前一个阶段的输出中跳过多少文档。

您可以使用 Aggregates.skip() 方法跳过前两个文档,如下所示

val filter = Filters.empty()
val results = collection.aggregate(listOf(
Aggregates.match(filter),
Aggregates.skip(2))
)

以下示例涉及一家销售八种不同颜色油漆的油漆店。最受欢迎的颜色比其他颜色的销售速度更快。有一天,一位顾客询问哪三种颜色是最受欢迎的(库存量最少)。油漆店通过其

paint_inventory

集合中的

qty

字段来跟踪库存。

{ "_id": 1, "color": "red", "qty": 5 }
{ "_id": 2, "color": "purple", "qty": 10 }
{ "_id": 3, "color": "blue", "qty": 9 }
{ "_id": 4, "color": "white", "qty": 6 }
{ "_id": 5, "color": "yellow", "qty": 11 }
{ "_id": 6, "color": "pink", "qty": 3 }
{ "_id": 7, "color": "green", "qty": 8 }
{ "_id": 8, "color": "orange", "qty": 7 }

该数据使用以下 Kotlin 数据类进行建模

data class PaintOrder(
@BsonId val id: Int,
val qty: Int,
val color: String
)

为了应对这种情况,油漆店需要使用空过滤器查询

paint_inventory

集合,按

qty

字段对文档进行排序,并忽略前五个结果。

val filter = Filters.empty()
val results = collection.find(filter)
.sort(descending(PaintOrder::qty.name))
.skip(5)
results.collect { println(it) }
PaintOrder(id=4, qty=6, color=white)
PaintOrder(id=1, qty=5, color=red)
PaintOrder(id=6, qty=3, color=pink)
  • find()方法返回所有文档。

  • sort()方法指定从最高到最低按

    qty

    字段显示文档。

  • skip()方法指定忽略前五个文档。

val filter = Filters.empty()
val aggregate = listOf(
Aggregates.match(filter),
Aggregates.sort(descending(PaintOrder::qty.name)),
Aggregates.skip(5)
)
val findFlow = collection.aggregate(aggregate)
findFlow.collect { println(it) }
PaintOrder(id=4, qty=6, color=white)
PaintOrder(id=1, qty=5, color=red)
PaintOrder(id=6, qty=3, color=pink)
  • match()阶段返回所有文档。

  • sort()阶段指定从最高到最低按

    qty

    字段显示文档。

  • skip()阶段指定忽略前五个文档。

油漆店运行查询后,发现最受欢迎的三种颜色是粉色、红色和白色。

注意

如果跳过的值大于或等于查询匹配的文档数,则该查询返回无文档。

如果前一个示例中的skip()方法跳过前九个文档,则不会返回任何结果,因为指定的数量超过了匹配的文档数。

val filter = Filters.empty()
val emptyQuery = listOf(
Aggregates.match(filter),
Aggregates.sort(descending(PaintOrder::qty.name)),
Aggregates.skip(9)
)
val findFlow = collection.aggregate(emptyQuery)
findFlow.collect { println(it) }

下一页

MongoDB Kotlin 驱动程序