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.以下示例描述了手动迭代游标以访问文档或使用迭代器索引的方法。
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:cursor
方法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 更改为其它数值。 |
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];
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 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
选项的信息,请参阅驱动程序文档。
As a cursor returns documents, other operations may interleave with the query.当游标返回文档时,其他操作可能与查询交错。
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
操作没有默认的批处理大小,因此它们仅受16MB消息大小的限制。
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();
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
字段,其中包含以下信息:
DBQuery.Option.noTimeout
set to prevent timeout after a period of inactivityDBQuery.Option.noTimeout
以防止在一段时间不活动后超时的打开游标数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> } }