cursor.limit()

On this page本页内容

Definition定义

cursor.limit()
Important重要
mongosh Method

This is a mongosh method. This is not the documentation for Node.js or other programming language specific driver methods.

In most cases, mongosh methods work the same way as the legacy mongo shell methods. However, some legacy methods are unavailable in mongosh.

For the legacy mongo shell documentation, refer to the documentation for the corresponding MongoDB Server release:

For MongoDB API drivers, refer to the language specific MongoDB driver documentation.

Use the limit() method on a cursor to specify the maximum number of documents the cursor will return. 在游标上使用limit()方法指定游标将返回的最大文档数。limit() is analogous to the LIMIT statement in a SQL database.limit()类似于SQL数据库中的LIMIT语句。

Note注意

You must apply limit() to the cursor before retrieving any documents from the database.在从数据库检索任何文档之前,必须对游标应用limit()

Use limit() to maximize performance and prevent MongoDB from returning more results than required for processing.使用limit()可最大限度地提高性能,并防止MongoDB返回超出处理要求的结果。

The limit() method has the following prototype form:limit()方法具有以下原型形式:

db.collection.find(<query>).limit(<number>)

Behavior行为

Supported Values支持的值

The behavior of limit() is undefined for values less than -2 31 and greater than 2 31.对于小于-231且大于231的值,limit()的行为未定义。

You must specify a numeric value for limit().必须为limit()指定一个数值。

Zero Value零值

A limit() value of 0 (i.e. .limit(0)) is equivalent to setting no limit.limit()值为0(即.limit(0))等同于没有设置限制。

Negative Values负值

A negative limit is similar to a positive limit but closes the cursor after returning a single batch of results. 负值限制类似于正值限制,但在返回一批结果后会关闭游标。As such, with a negative limit, if the limited result set does not fit into a single batch, the number of documents received will be less than the specified limit. 因此,如果限制结果集不适合单个批次,则使用负限制时,收到的文档数将小于指定的限制。By passing a negative limit, the client indicates to the server that it will not ask for a subsequent batch via getMore.通过传递一个负数限制,客户端向服务器指示它不会通过getMore请求后续批处理。

Using limit() with sort()使用limit()配合sort()

If using limit() with sort(), be sure to include at least one field in your sort that contains unique values, before passing results to limit().如果将limit()sort()结合使用,在将结果传递给limit()之前,请确保在排序中至少包含一个包含唯一值的字段。

Sorting on fields that contain duplicate values may return an inconsistent sort order for those duplicate fields over multiple executions, especially when the collection is actively receiving writes.对包含重复值的字段进行排序可能会在多次执行中返回这些重复字段的不一致排序顺序,尤其是当集合正在积极接收写入时。

The easiest way to guarantee sort consistency is to include the _id field in your sort query.确保排序一致性的最简单方法是在排序查询中包含_id字段。

See Consistent sorting with the sort() method for more information.有关详细信息,请参阅使用sort()方法进行一致排序

←  cursor.itcount()cursor.map() →