OPTIONS
翻译或纠错本页面

mongo 命令行里迭代游标

The db.collection.find() method returns a cursor. 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 to print up to the first 20 documents in the results. The following describes ways to manually iterate the cursor to access the documents or to use the iterator index.

手动迭代游标

mongo 命令行里,当你使用 var 关键字把 find() 方法返回的游标赋值给一个变量时,它将不会自动迭代。

在命令行里,你可以调用游标变量迭代最多20次 [1] 并且打印那么匹配的文档,如下例所示:

var myCursor = db.inventory.find( { type: 'food' } );

myCursor

你也可以使用游标的 next() 方法来访问文档,如下例所示:

var myCursor = db.inventory.find( { type: 'food' } );

while (myCursor.hasNext()) {
   print(tojson(myCursor.next()));
}

作为一种替代的打印操作,考虑使用 printjson() 助手方法来替代 print(tojson())

var myCursor = db.inventory.find( { type: 'food' } );

while (myCursor.hasNext()) {
   printjson(myCursor.next());
}

你可以使用游标方法 forEach() 来迭代游标并且访问文档,如下例所示:

var myCursor =  db.inventory.find( { type: 'food' } );

myCursor.forEach(printjson);

参见 ref:JavaScript cursor methods <js-query-cursor-methods>driver 文档来获取更多关于游标方法的资料。

[1]

你可以使用 DBQuery.shellBatchSize 来改变迭代次数的默认值 20。请参考 ref:mongo-shell-executing-queries 获取更多资料。

迭代器索引

mongo`命令行里,你可以使用 :method:`~cursor.toArray() 方法来迭代游标,并且以数组的形式来返回文档,如下例所示:

var myCursor = db.inventory.find( { type: 'food' } );
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.

另外,一些 驱动 通过在游标上使用索引来提供访问文档的方法(例如 cursor[index] )。对于第一次调用 toArray() 方法这是一个捷径,然后可以在数组结果上使用索引。

请考虑下面的示例:

var myCursor = db.inventory.find( { type: 'food' } );
var myDocument = myCursor[3];

The myCursor[3] is equivalent to the following example:

myCursor.toArray() [3];