跳过返回结果
概述
在本指南中,您将学习如何使用MongoDB Java驱动程序从读取操作中跳过指定数量的返回结果。
您可以通过使用skip()
方法来跳过查询的返回结果。您还可以通过指定一个$skip
聚合阶段来跳过聚合管道中特定阶段的文档。
skip()
方法接受一个整数,指定要跳过FindIterable返回的文档列表开头的文档数量。FindIterable.
您可以使用skip()
方法跳过前两个文档,如下所示
collection.find().skip(2);
Aggregates.skip()是聚合管道中的一个可选阶段,指定从上一阶段的结果中跳过多少个文档。
您可以使用Aggregates.skip()
方法跳过前两个文档,如下所示
import com.mongodb.client.model.Aggregates; collection.aggregate(Arrays.asList(Aggregates.match(), 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 }
为了解决这种情况,油漆店需要使用空过滤器查询
paint_inventory
集合,按qty
字段排序并省略前五个结果。使用FindIterable
import com.mongodb.client.model.Filters; import com.mongodb.client.model.Sorts; // Add your MongoCollection setup code here Bson filter = Filters.empty(); collection.find(filter) .sort(Sorts.descending("qty")) .skip(5) .forEach(doc -> System.out.println(doc.toJson()));
find()
方法返回所有文档。sort()
方法指定根据qty
字段从高到低显示文档。skip()
方法指定省略前五个文档。
使用聚合
import com.mongodb.client.model.Filters; import com.mongodb.client.model.Sorts; import com.mongodb.client.model.Aggregates; // Add your MongoCollection setup code here Bson filter = Filters.empty(); collection.aggregate(Arrays.asList( Aggregates.match(filter), Aggregates.sort(Sorts.descending("qty")), Aggregates.skip(5))) .forEach(doc -> System.out.println(doc.toJson()));
match()
阶段返回所有文档。sort()
阶段指定根据qty
字段从高到低显示文档。skip()
阶段指定省略前五个文档。
以下展示了前两个查询的输出
{ "_id": 4, "color": "white", "qty": 6 } { "_id": 1, "color": "red", "qty": 5 } { "_id": 6, "color": "pink", "qty": 3 }
油漆店运行查询后,发现销量最好的三种颜色是粉色、红色和白色。
注意
如果跳过的值大于或等于查询匹配的文档数量,则该查询返回没有文档。
如果前面的例子中的skip()
方法跳过了前九个文档,由于指定的数量超过了匹配的文档数量,因此不会返回任何结果。
Bson filter = Filters.empty(); collection.find(filter) .sort(Sorts.descending("qty")) .skip(9) .forEach(doc -> System.out.println(doc.toJson()));