MongoDB Java 驱动程序 v4.3 分页

发布时间:2022-07-04 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了MongoDB Java 驱动程序 v4.3 分页脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

官方文档:https://docs.mongodb.COM/drivers/java/sync/current/fundamentals/crud/read-operations/skip/

 

跳过返回的结果

概览

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

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

skip()方法采用一个整数,指定要从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)));

 

例子

以下示例是关于一家销售八种不同颜色油漆的油漆店。最好的颜色比其他颜色卖得更快。一天,一位客户询问最畅销(库存最低)的三种颜色是什么油漆店qty 在他们的paint_inventory收藏中跟踪现场的库存

{ "_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;
// <;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;
// <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 的值大于或等于查询的匹配文档数,则该查询不返回任何文档。

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

Bson filter = Filters.empty();
collection.find(filter)             
    .sort(Sorts.descending("qty"))        
    .skip(9)                       
    .forEach(doc -> System.out.println(doc.toJson()));

 

限制返回结果的数量

概览

在本指南中,您可以了解如何使用 MongoDB Java 驱动程序限制读取操作返回的结果数量。

使用limit()封顶的文档的读取操作返回的数量。此实例方法指定读取操作可以返回的最大文档数。如果没有足够的文件达到指定的限制,它可以返回一个较小的数字。如果limit()skip()实例方法一起使用,则首先应用跳过,限制仅适用于跳过后剩余的文档。有关该skip()方法的更多信息,请参阅我们的 跳过退回文件指南

下面的例子分别演示了如何将数据插入到集合中,如何使用limit()来限制返回文档的数量,以及如何结合limit()使用skip()来进一步缩小查询返回的结果。

示例文档

以下操作将代表书籍的文档插入到集合中:

collection.insertMany(Arrays.asList(
    new Document().apPEnd("_id", 1)
        .append("title", "The brothers Karamazov").append("length", 824)
        .append("author", "DOStoyevsky"),
    new Document().append("_id", 2)
        .append("title", "Les Misérables").append("length", 1462).append("author", "Hugo"),
    new Document().append("_id", 3)
        .append("title", "Atlas Shrugged").append("length", 1088).append("author", "Rand"),
    new Document().append("_id", 4)
        .append("title", "Infinite Jest").append("length", 1104).append("author", "Wallace"),
    new Document().append("_id", 5)
        .append("title", "Cryptonomicon").append("length", 918).append("author", "Stephenson"),
    new Document().append("_id", 6)
        .append("title", "A Dance with Dragons").append("length", 1104)
        .append("author", "Martin")
));

 

指定限制

下一个示例查询集合以返回前三本最长的书。它首先将所有文档与查询匹配,然后在length字段上排序以在 长度较短的书籍之前返回长度较长的书籍。最后,它将返回值限制为3文档:

  import com.mongodb.client.model.Sorts;
  // define a cursor that will return the First 3 sorted items
  MongoCursor<Document> cursor = collection.find()
      .sort(descending("length"))
      .limit(3)
      .iterator();
  // print out items
  try {
      while (cursor.hasNext()) {
          System.out.println(cursor.next());
      }
  }
  // close the cursor
  finally {
      cursor.close();
  }

 

前面的代码示例打印出以下三个文档,按长度排序:

 Document{{_id=2, title=Les Misérables, author=Hugo, length=1462}}
 Document{{_id=6, title=A Dance with Dragons, author=Martin, length=1104}}
 Document{{_id=4, title=Infinite Jest, author=Wallace, length=1104}}

 

提示

您调用limit()的顺序sort()无关紧要,因为驱动程序重新排序调用以先应用排序,然后应用限制。以下两个调用是等效的:

collection.find().sort(descending("length")).limit(3);
collection.find().limit(3).sort(descending("length"));

 

结合跳过和限制

要查看接下来最长的三本书,请将skip()方法附加到您的 find()调用中。传递给的整数参数skip()将决定查找操作返回多少文档:

  MongoCursor<Document> cursor = collection.find()
      .sort(ascending("length"))
      .limit(3)
      .skip(3)
      .iterator();

 

此操作返回描述第四到第六长书籍的文档:

 Document{{_id=3, title=Atlas Shrugged, author=Rand, length=1088}}
 Document{{_id=5, title=Cryptonomicon, author=Stephenson, length=918}}
 Document{{_id=1, title=The Brothers Karamazov, author=Dostoyevsky, length=824}}

 

您可以结合skip()limit()以这种方式为您的集合实现分页,一次只返回集合的一小部分。

笔记

为了确保跨多个查询的稳定排序,您必须使用唯一键(例如_id)进行排序否则,当与 结合使用时,对skip() 和的调用limit()可能会产生不可预测的结果 sort()

例如,考虑以下数据:

 { type: "computer", data: "1", serial_no: 235235 }
 { type: "computer", data: "2", serial_no: 235237 }
 { type: "computer", data: "3", serial_no: 235239 }
 { type: "computer", data: "4", serial_no: 235241 }

 

如果您type单独排序sort()不保证返回时的顺序相同。追加skip()limit()sort() 可以返回不同的查询不同的文件。在这种情况下,按dataor排序serial_no将保证稳定排序,因为两者都是唯一键。

 

脚本宝典总结

以上是脚本宝典为你收集整理的MongoDB Java 驱动程序 v4.3 分页全部内容,希望文章能够帮你解决MongoDB Java 驱动程序 v4.3 分页所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。