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. 解决Ubuntu16.04 fatal error: json/json.h: No such file or directory

    参考博客 错误产生 安装json-c库之后,根据GitHub上面的readme文件链接到json-c库时出现以下错误: SDMBNJson.h:9:23: fatal error: json/json ...

  2. JSON.parse与eval

    文章:JSON.parse 与 eval() 对于解析json的问题 json的标准格式:{"name":"jobs"}   名字和值都必须用双引号引起来.

  3. Maven基本理解

    转 maven(一) maven到底是个啥玩意~ 我记得在搞懂maven之前看了几次重复的maven的教学视频.不知道是自己悟性太低还是怎么滴,就是搞不清楚,现在弄清楚了,基本上入门了.写该篇博文,就 ...

  4. 自签证书 doesn't match any of the subject alternative names

    出现这个的原因是https中的域名或者IP,与证书中登记的不一致. 如果是自签证书的话,可以根据具体需要重新生成证书. 还有一种解决方案是在java中跳过这个检查. 绕过检查分两类,一个是绕过证书在C ...

  5. MacOS & 如何在当前文件下打开 terminal

    MacOS & 如何在当前文件下打开 terminal macbook 如何在文件夹中 打开 terminal https://www.cnblogs.com/yjmyzz/p/3662507 ...

  6. 解决Lenovo(ldeapad)笔记本F1-F12功能键操作无效的问题

    1.操作条件:Lenovo笔记本自带的“一键恢复”按钮 2.操作方法:上下键为切换选项,回车键(Enter)为确定选择 (1)在笔记本电脑关机状态下,使用曲别针或其他物件按下笔记本自带的“一键恢复按钮 ...

  7. 第81天:jQuery 插件使用方法

    在追求页面互动效果的时代,大家都想把页面效果做的美轮美奂,这一切都离不开前端技术脚本Javascript,而最近常被人用到的Javascript库文件则是jQuery.  jQuery的使用具体步骤如 ...

  8. stm32中使用#pragma pack(非常有用的字节对齐用法说明)

    #pragma pack(4)   //按4字节对齐,但实际上由于结构体中单个成员的最大占用字节数为2字节,因此实际还是按2字节对齐 typedef struct { char buf[3];//bu ...

  9. python写BMI指数菜单

    需求: # 1.创建并输出菜单, 菜单是不可变的. 所以使用元组menus = ("1, 录入", "2, 查询", "3, 删除", &q ...

  10. hbase 基本的JavaApi 数据操作及数据过滤(filter)

    本文主要是hbase的表操作.数据操作.数据查询过滤等,如果对JDBC或ADO有了解,容易理解HBASE API. hbase版本是2.0. 1.为了方便先贴helper的部分代码(文末git上有完整 ...