限制返回结果的数目
概述
在本指南中,您可以了解如何使用 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.*; import org.bson.Document; import static com.mongodb.client.model.Sorts.descending; // ... // 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 和 Limit
要查看下一本最长的三本书,将 skip()
方法添加到您的 find()
调用中,如下面的代码示例所示
MongoCursor<Document> cursor = collection.find() .sort(descending("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
)进行排序。否则,当与 sort()
结合使用时,skip()
和 limit()
可能会产生不可预测的结果。
例如,考虑以下数据
{ 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()
可能会根据不同的查询返回不同的文档。在这种情况下,按 data
或 serial_no
排序将保证稳定的排序,因为这两个都是唯一键。
有关本指南中提到的方法和类的更多信息,请参阅以下 API 文档