Iterate a Cursor in the mongo Shellmongo Shell中迭代游标

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 the mongo shell, 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.但是,在mongo shell中,如果返回的游标未使用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 the mongo shell, when you assign the cursor returned from the find() method to a variable using the var keyword, the cursor does not automatically iterate.mongo shell中,当使用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) You can use the DBQuery.shellBatchSize to change the number of iteration from the default value 20. 可以使用DBQuery.shellBatchSize将迭代次数从默认值20更改为其它数字。See Working with the mongo Shell for more information.有关更多信息,请参阅使用mongo Shell

Iterator Index迭代器索引

In the mongo shell, you can use the toArray() method to iterate the cursor and return the documents in an array, as in the following:mongo shell中,您可以使用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游标行为

Closure of Inactive Cursors关闭非活动游标

By default, the server will automatically close the cursor after 10 minutes of inactivity, or if client has exhausted the cursor. 默认情况下,服务器将在10分钟不活动后自动关闭游标,或者如果客户端耗尽了游标。To override this behavior in the mongo shell, you can use the cursor.noCursorTimeout() method:要在mongo shell中重写此行为,可以使用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()

New in version 3.4:3.4版中的新版本:Operations of type find(), aggregate(), listIndexes, and listCollections return a maximum of 16 megabytes per batch. find()aggregate()listIndexeslistCollections类型的操作每批最多返回16 MB。batchSize() can enforce a smaller limit, but not a larger one.batchSize()可以执行较小的限制,但不能执行较大的限制。

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();

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字段,其中包含以下信息:

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()方法,从结果中访问度量字段,然后从度量字段访问游标字段:

db.serverStatus().metrics.cursor

The result is the following document:结果是以下文件:

{
   "timedOut" : <number>
   "open" : {
      "noTimeout" : <number>,
      "pinned" : <number>,
      "total" : <number>
   }
}

See also参阅

db.serverStatus()