1 迭代游标

var myCursor = db.users.find( { type: 2 } );

while (myCursor.hasNext()) {
print(tojson(myCursor.next()));
}
var myCursor =  db.users.find( { type: 2 } );

myCursor.forEach(printjson);

2 迭代指数

var myCursor = db.inventory.find( { type: 2 } );
var documentArray = myCursor.toArray();
var myDocument = documentArray[];

可以简化成

var myCursor = db.users.find( { type: 2 } );
var myDocument = myCursor[];

3 关闭游标,不活跃的游标需要等到10分钟才自动关闭,可以通过指定时间来进行关闭

var myCursor = db.users.find().noCursorTimeout();

4  find()aggregate()listIndexes, and listCollections 最大是16MB

var myCursor = db.inventory.find();

var myFirstDocument = myCursor.hasNext() ? myCursor.next() : null;

myCursor.objsLeftInBatch();

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 varkeyword, then the cursor is automatically iterated up to 20 times [1] to print up to the first 20 documents in the results.

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 varkeyword, the cursor does not automatically iterate.

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:

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:

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

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:

var myCursor =  db.users.find( { type: 2 } );

myCursor.forEach(printjson);

See JavaScript cursor methods and your driver documentation for more information on cursor methods.

[1] (12) You can use the DBQuery.shellBatchSize to change the number of iteration from the default value 20. SeeWorking with the mongo Shell for more information.

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:

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.

Additionally, some drivers provide access to the documents by using an index on the cursor (i.e.cursor[index]). This is a shortcut for first calling the toArray() method and then using an index on the resulting array.

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.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. To override this behavior in the mongo shell, you can use the cursor.noCursorTimeout()method:

var myCursor = db.users.find().noCursorTimeout();

After setting the noCursorTimeout option, you must either close the cursor manually withcursor.close() or by exhausting the cursor’s results.

See your driver documentation for information on setting the noCursorTimeout option.

Cursor Isolation

As a cursor returns documents, other operations may interleave with the query. For the MMAPv1 storage engine, intervening write operations on a document may result in a cursor that returns a document more than once if that document has changed. To handle this situation, see the information on snapshot mode.

Cursor Batches

The MongoDB server returns the query results in batches. The amount of data in the batch will not exceed themaximum BSON document size. To override the default size of the batch, see batchSize() and limit().

New in version 3.4: Operations of type find()aggregate()listIndexes, and listCollectionsreturn a maximum of 16 megabytes per batch. 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. SubsequentgetMore operations issued against the resulting cursor have no default batch size, so they are limited only by the 16 megabyte message size.

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. 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:

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. The metrics field contains a metrics.cursor field with the following information:

  • number of timed out cursors since the last server restart
  • number of open cursors with the option DBQuery.Option.noTimeout set to prevent timeout after a period of inactivity
  • number of “pinned” open cursors
  • total number of open cursors

Consider the following example which calls the db.serverStatus() method and accesses the metricsfield from the results and then the cursor field from the metrics field:

db.serverStatus().metrics.cursor

The result is the following document:

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

14.Iterate a Cursor in the mongo Shell-官方文档摘录的更多相关文章

  1. 2.Access the mongo Shell Help-官方文档摘录

    总结: 1.使用help可以查看帮助信息db.help()  help等 2.查看对应的实现方法.比如 test@gzxkvm52$ db.updateUser function (name, upd ...

  2. MongoDB - MongoDB CRUD Operations, Query Documents, Iterate a Cursor in the mongo Shell

    The db.collection.find() method returns a cursor. To access the documents, you need to iterate the c ...

  3. 1.Configure the mongo Shell-官方文档摘录

    Customize the Prompt 自定义提示 You may modify the content of the prompt by setting the variable prompt i ...

  4. 3.Write Scripts for the mongo Shell-官方文档摘录

    总结 1 使用js进行获取数据的方法 2 js方式和原生mongo shell的交互方式的区别写法 3 需要将所有数据打印出来使用到的循环示例 cursor = db.collection.find( ...

  5. 4.Data Types in the mongo Shell-官方文档摘录

    总结: 1.MongoDB 的BSON格式支持额外的数据类型 2 Date 对象内部存储64位字节存整数,存储使用NumberLong()这个类来存,使用NumberInt()存32位整数,128位十 ...

  6. MongoDB - The mongo Shell, mongo Shell Quick Reference

    mongo Shell Command History You can retrieve previous commands issued in the mongo shell with the up ...

  7. MongoDB - Introduction of the mongo Shell

    Introduction The mongo shell is an interactive JavaScript interface to MongoDB. You can use the mong ...

  8. MongoDB基本增删改查操作-mongo shell

    基础 1.查看所有数据库: show dbs 2.选择数据库: use test 3.查看数据库中有哪些集合: show collections 如下图: 查询 1.查看集合中有哪些数据,其中abc为 ...

  9. MongoDB - The mongo Shell, Configure the mongo Shell

    Customize the Prompt You may modify the content of the prompt by setting the variable prompt in the  ...

随机推荐

  1. 一款基于css3的散子3D翻转特效

    css3使我们能够跳出2d空间,实现3维空间的动画效果,这里给出一个自动翻转的3d色子动画效果制作过程. 第一步,首先进行HTML的布局,对于3D效果,布局有一定的规律,代码如下: <body& ...

  2. boost准模板库内存管理中pool和object_pool的使用

    首先,在敲代码之前,必须改动一个问题.要不然,无法链接: boost安装文件夹:D:\boost.       找到D:\boost\boost_1_55_0\include\boost-1_55\b ...

  3. spring配置:context:property-placeholder 读取配置文件信息 在配置文件中使用el表达式填充值

    spring将properties文件读取后在配置文件中直接将对象的配置信息填充到bean中的变量里. 原本使用PropertyPlaceholderConfigurer类进行文件信息配置.Prope ...

  4. lnmp服务器的目录信息

    LNMP状态管理命令: LNMP状态管理: /root/lnmp {start|stop|reload|restart|kill|status}Nginx状态管理:/etc/init.d/nginx ...

  5. Goroutine并发调度模型深度解析之手撸一个协程池

    golanggoroutine协程池Groutine Pool高并发 并发(并行),一直以来都是一个编程语言里的核心主题之一,也是被开发者关注最多的话题:Go语言作为一个出道以来就自带 『高并发』光环 ...

  6. 001jsp的基本知识-包括生命周期,怎么编译等等

    4 Jsp基础 4.1 Jsp引入 Servlet的作用: 用java语言开发动态资源的技术!!! Jsp的作用:用java语言(+html语言)开发动态资源的技术!!! Jsp就是servlet!! ...

  7. jQuery补充,模拟图片放大镜

    jQuery补充,模拟图片放大镜 html <!DOCTYPE html> <html lang="en"> <head> <meta c ...

  8. 【BZOJ】1613: [Usaco2007 Jan]Running贝茜的晨练计划(dp)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1613 水题dp 设d[i][j]为i分钟疲劳为j d[i][j]=d[i-1][j-1]+a[i] ...

  9. LandMVC HttpHandler web.config配置

    <system.webServer> <validation validateIntegratedModeConfiguration="false" /> ...

  10. [转]Shell脚本中发送html邮件的方法

    <span "="">作为运维人员,免不了要编写一些监控脚本,并将监控结果及时的发送出来.那么通过邮件发送是比较常用的一种通知方式了.通常的,如果需要发送的内 ...