Iterate a Cursor in mongosh
在mongosh
中迭代游标
mongosh
On this page本页内容
The db.collection.find()
method returns a cursor. db.collection.find()
方法返回一个游标。To access the documents, you need to iterate the cursor. 要访问文档,您需要迭代游标。However, in 然而,在mongosh
, if the returned cursor is not assigned to a variable using the var
keyword, then the cursor is automatically iterated up to 20 times [1] to print up to the first 20 documents in the results.mongosh
中,如果返回的游标没有使用var
键分配给变量,则游标会自动迭代20次[1],以打印结果中的前20个文档。
The following examples describe ways to manually iterate the cursor to access the documents or to use the iterator index.以下示例描述了手动迭代游标以访问文档或使用迭代器索引的方法。
Manually Iterate the Cursor手动迭代游标
In 在mongosh
, when you assign the cursor returned from the find()
method to a variable using the var
keyword, the cursor does not automatically iterate.mongosh
中,当您使用var
键将find()
方法返回的游标分配给变量时,游标不会自动迭代。
You can call the cursor variable in the shell to iterate up to 20 times [1] and print the matching documents, as in the following example:您可以调用shell中的游标变量,最多迭代20次[1]并打印匹配的文档,如下例所示:
var myCursor = db.users.find( { type: 2 } );
myCursor
You can also use the cursor method 您也可以使用游标方法next()
to access the documents, as in the following example:next()
来访问文档,如下例所示:
var myCursor = db.users.find( { type: 2 } );
while (myCursor.hasNext()) {
print(tojson(myCursor.next()));
}
As an alternative print operation, consider the 作为另一种打印操作,请考虑使用printjson()
helper method to replace print(tojson())
:printjson()
助手方法来替换print(tojson())
:
var myCursor = db.users.find( { type: 2 } );
while (myCursor.hasNext()) {
printjson(myCursor.next());
}
You can use the cursor method 您可以使用游标方法forEach()
to iterate the cursor and access the documents, as in the following example:forEach()
来迭代游标并访问文档,如下例所示:
var myCursor = db.users.find( { type: 2 } );
myCursor.forEach(printjson);
See JavaScript cursor methods and your driver documentation for more information on cursor methods.有关游标方法的更多信息,请参阅JavaScript游标方法和驱动程序文档。
[1] | (1, 2) DBQuery.shellBatchSize attribute to change the number of documents from the default value of 20 .DBQuery.shellBatchSize 属性来更改默认值20 的文档数。 |
Iterator Index迭代程序索引
In 在mongosh
, you can use the toArray()
method to iterate the cursor and return the documents in an array, as in the following:mongosh
中,可以使用toArray()
方法迭代游标并返回数组中的文档,如下所示:
var myCursor = db.inventory.find( { type: 2 } );
var documentArray = myCursor.toArray();
var myDocument = documentArray[3];
The toArray()
method loads into RAM all documents returned by the cursor; the toArray()
method exhausts the cursor.toArray()
方法将游标返回的所有文档加载到RAM中;toArray()
方法会耗尽游标。
Additionally, some Drivers provide access to the documents by using an index on the cursor (i.e. 此外,一些驱动程序通过使用游标上的索引(即cursor[index]
). cursor[index]
)来提供对文档的访问。This is a shortcut for first calling the 这是一个快捷方式,用于首先调用toArray()
method and then using an index on the resulting array.toArray()
方法,然后对生成的数组使用索引。
Consider the following example:考虑以下示例:
var myCursor = db.users.find( { type: 2 } );
var myDocument = myCursor[1];
The myCursor[1]
is equivalent to the following example:myCursor[1]
等效于以下示例:
myCursor.toArray() [1];
Cursor Behaviors游标行为
Cursors Opened Within a Session会话中打开的游标
Starting in MongoDB 5.0 (and 4.4.8), cursors created within a client session close when the corresponding server session ends with the 从MongoDB 5.0(和4.4.8)开始,当相应的服务器会话以killSessions
command, if the session times out, or if the client has exhausted the cursor.killSessions
命令结束时,如果会话超时,或者如果客户端耗尽了游标,则在客户端会话中创建的游标将关闭。
By default, server sessions have an expiration timeout of 30 minutes. 默认情况下,服务器会话的过期超时为30分钟。To change the value, set the 要更改该值,请在启动localLogicalSessionTimeoutMinutes
parameter when starting up mongod
.mongod
时设置localLogicalSessionTimeoutMinutes
参数。
Cursors Opened Outside of a Session在会话之外打开的游标
Cursors that aren't opened under a session automatically close after 10 minutes of inactivity, or if client has exhausted the cursor. 会话中未打开的游标在10分钟不活动后自动关闭,或者如果客户端已耗尽游标。To override this behavior in 要在mongosh
, you can use the cursor.noCursorTimeout()
method:mongosh
中覆盖此行为,可以使用cursor.noCursorTimeout()
方法:
var myCursor = db.users.find().noCursorTimeout();
After setting the 设置noCursorTimeout
option, you must either close the cursor manually with cursor.close()
or by exhausting the cursor's results.noCursorTimeout
选项后,必须使用cursor.close()
手动关闭游标,或者通过耗尽游标的结果来关闭游标。
See your driver documentation for information on setting the 有关设置noCursorTimeout
option.noCursorTimeout
选项的信息,请参阅驱动程序文档。
Cursor Isolation游标隔离
As a cursor returns documents, other operations may interleave with the query.当游标返回文档时,其他操作可能会与查询交织在一起。
Cursor Batches游标批
The MongoDB server returns the query results in batches. MongoDB服务器批量返回查询结果。The amount of data in the batch will not exceed the maximum BSON document size. 批处理中的数据量不会超过BSON文档的最大大小。To override the default size of the batch, see 要覆盖批次的默认大小,请参阅batchSize()
and limit()
.batchSize()
和limit()
。
Operations of type find()
, aggregate()
, listIndexes
, and listCollections
return a maximum of 16 megabytes per batch. find()
、aggregate()
、listIndexes
和listCollections
类型的操作每批最多返回16兆字节。batchSize()
can enforce a smaller limit, but not a larger one.可以执行较小的限制,但不能执行较大的限制。
find()
and aggregate()
operations have an initial batch size of 101 documents by default. find()
和aggregate()
操作的初始批处理大小默认为101个文档。Subsequent 针对生成的游标发出的后续getMore
operations issued against the resulting cursor have no default batch size, so they are limited only by the 16 megabyte message size.getMore
操作没有默认的批处理大小,因此它们仅受16兆字节消息大小的限制。
For queries that include a sort operation without an index, the server must load all the documents in memory to perform the sort before returning any results.对于包含不带索引的排序操作的查询,服务器必须在返回任何结果之前加载内存中的所有文档以执行排序。
As you iterate through the cursor and reach the end of the returned batch, if there are more results, 当您遍历游标并到达返回批次的末尾时,如果有更多结果,cursor.next()
will perform a getMore operation
to retrieve the next batch. cursor.next()
将执行getMore
操作来检索下一个批次。To see how many documents remain in the batch as you iterate the cursor, you can use the 要查看迭代游标时批处理中还有多少文档,可以使用objsLeftInBatch()
method, as in the following example:objsLeftInBatch()
方法,如下例所示:
var myCursor = db.inventory.find();
var myFirstDocument = myCursor.hasNext() ? myCursor.next() : null;
myCursor.objsLeftInBatch();
Cursor Information游标信息
The db.serverStatus()
method returns a document that includes a metrics
field. db.serverStatus()
方法返回一个包含metrics
字段的文档。The metrics
field contains a metrics.cursor
field with the following information:metrics
字段包含一个metrics.cursor
字段,其中包含以下信息:
number of timed out cursors since the last server restart自上次服务器重新启动以来超时的游标数number of open cursors with the optionDBQuery.Option.noTimeout
set to prevent timeout after a period of inactivityDBQuery.Option.noTimeout
选项设置为防止在一段时间不活动后超时的打开游标数number of "pinned" open cursors“固定”打开的游标数total number of open cursors打开的游标总数
Consider the following example which calls the 考虑以下示例,该示例调用db.serverStatus()
method and accesses the metrics
field from the results and then the cursor
field from the metrics
field:db.serverStatus()
方法并从结果中访问metrics
字段,然后从metrics
字段中访问cursor
字段:
db.serverStatus().metrics.cursor
The result is the following document:结果是以下文件:
{
"timedOut" : <number>
"open" : {
"noTimeout" : <number>,
"pinned" : <number>,
"total" : <number>
}
}