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

You can call the cursor variable in the shell to iterate up to 20 times and print the matching documents, as in the following example:

> var myCursor = db.users.find( { type: 2 } );
> myCursor
{ "_id" : 3, "name" : "ahn", "age" : 22, "type" : 2, "status" : "A", "favorites" : { "artist" : "Cassatt", "food" : "cake" }, "finished" : [ 6 ], "badges" : [ "blue", "red" ], "points" : [ { "points" : 81, "bonus" : 8 }, { "points" : 55, "bonus" : 20 } ] }
{ "_id" : 4, "name" : "xi", "age" : 34, "type" : 2, "status" : "D", "favorites" : { "artist" : "Chagall", "food" : "chocolate" }, "finished" : [ 5, 11 ], "badges" : [ "red", "black" ], "points" : [ { "points" : 53, "bonus" : 15 }, { "points" : 51, "bonus" : 15 } ] }
{ "_id" : 5, "name" : "xyz", "age" : 23, "type" : 2, "status" : "D", "favorites" : { "artist" : "Noguchi", "food" : "nougat" }, "finished" : [ 14, 6 ], "badges" : [ "orange" ], "points" : [ { "points" : 71, "bonus" : 20 } ] }

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.

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 with cursor.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. Batch size will not exceed the maximum BSON document size. For most queries, the first batch returns 101 documents or just enough documents to exceed 1 megabyte. Subsequent batch size is 4 megabytes. To override the default size of the batch, see batchSize() and limit().

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>
}
}

SEE ALSO: db.serverStatus()

MongoDB - MongoDB CRUD Operations, Query Documents, Iterate a Cursor in the mongo Shell的更多相关文章

  1. MongoDB - MongoDB CRUD Operations, Query Documents, Project Fields to Return from Query

    By default, queries in MongoDB return all fields in matching documents. To limit the amount of data ...

  2. MongoDB - MongoDB CRUD Operations, Query Documents

    Query Method MongoDB provides the db.collection.find() method to read documents from a collection. T ...

  3. MongoDB - MongoDB CRUD Operations, Query Documents, Query for Null or Missing Fields

    Different query operators in MongoDB treat null values differently. The examples on this page use th ...

  4. 14.Iterate a Cursor in the mongo Shell-官方文档摘录

    1 迭代游标 } ); while (myCursor.hasNext()) { print(tojson(myCursor.next())); } } ); myCursor.forEach(pri ...

  5. MongoDB - MongoDB CRUD Operations, Delete Documents

    Delete Methods MongoDB provides the following methods to delete documents of a collection: Method De ...

  6. MongoDB - MongoDB CRUD Operations, Insert Documents

    MongoDB provides the following methods for inserting documents into a collection: db.collection.inse ...

  7. MongoDB - MongoDB CRUD Operations, Update Documents

    Update Methods MongoDB provides the following methods for updating documents in a collection: Method ...

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

  9. MongoDB - Introduction of the mongo Shell

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

随机推荐

  1. BETA事后总结

    目录 所有成员 项目宣传视频链接 贡献比例 工作流程 组员分工 本组 Beta 冲刺站立会议博客链接汇总 燃尽图 原计划.达成情况及原因分析 组员:胡绪佩 组员:周政演 组员:庄卉 组员:何家伟 组员 ...

  2. vue-cli脚手架搭建

    我们使用vue-cli来搭建整个项目,vue-cli就是一个脚手架,步骤很简单,输入几个命令之后就会生成整个项目,里面包括了webpack.ESLint.babel很多配置等等,省了很多事 Vue+ ...

  3. kafka describe 显示结果解释

    > bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic my-replicated-topic Topic:my- ...

  4. mysql中事务

    事务控制语言 什么叫做“事务”: 想象一个场景: 小明给小花 汇款 5000元 买 IPHONE,操作界面不用管,不管什么操作界面,最终都要落实到这样两条语句的执行: update  存款表  set ...

  5. 守护线程以及要使用时注意的一点(Daemon Thread)

    在Java中有两类线程:User Thread(用户线程).Daemon Thread(守护线程) Daemon的作用是为其他线程的运行提供便利服务,比如垃圾回收线程就是一个很称职的守护者.User和 ...

  6. IPv4编址及子网划分

    在讨论IP编址之前,我们需要讨论一下主机与路由器连入网络的方法.一台主机通常只有一条链路链接到网络:当主机中的IP想发送一个数据报时,它就在链路上发送,主机与物理链路之间的边界叫做接口(interfa ...

  7. 第84天:jQuery动态创建表格

    jQuery动态创建表格 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...

  8. 对Spark2.2.0文档的学习1-Cluster Mode Overview

    Cluster Mode Overview Link:http://spark.apache.org/docs/2.2.0/cluster-overview.html Spark应用(Applicat ...

  9. Java虚拟机内存模型和volatile型变量

    Java虚拟机内存模型 了解Java虚拟机的内存模型,有助于我们明白为什么会发生线程安全问题. 上面这幅图是<深入理解Java虚拟机-JVM高级特性与最佳实践>的书中截图. 线程共享的变量 ...

  10. Tomcat+JDK安装和配置

    Tomcat+JDK安装和配置 一.打开FlashFXP软件,建立连接,选择需要的包,右击传输到 /home/guest中 二.进入到:cd /home/guest中,对tomcat包进行解压 三.将 ...