14.Iterate a Cursor in the mongo Shell-官方文档摘录
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 var
keyword, 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 var
keyword, 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] | (1, 2) 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 listCollections
return 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 metrics
field 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
14.Iterate a Cursor in the mongo Shell-官方文档摘录的更多相关文章
- 2.Access the mongo Shell Help-官方文档摘录
总结: 1.使用help可以查看帮助信息db.help() help等 2.查看对应的实现方法.比如 test@gzxkvm52$ db.updateUser function (name, upd ...
- 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 ...
- 1.Configure the mongo Shell-官方文档摘录
Customize the Prompt 自定义提示 You may modify the content of the prompt by setting the variable prompt i ...
- 3.Write Scripts for the mongo Shell-官方文档摘录
总结 1 使用js进行获取数据的方法 2 js方式和原生mongo shell的交互方式的区别写法 3 需要将所有数据打印出来使用到的循环示例 cursor = db.collection.find( ...
- 4.Data Types in the mongo Shell-官方文档摘录
总结: 1.MongoDB 的BSON格式支持额外的数据类型 2 Date 对象内部存储64位字节存整数,存储使用NumberLong()这个类来存,使用NumberInt()存32位整数,128位十 ...
- 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 ...
- MongoDB - Introduction of the mongo Shell
Introduction The mongo shell is an interactive JavaScript interface to MongoDB. You can use the mong ...
- MongoDB基本增删改查操作-mongo shell
基础 1.查看所有数据库: show dbs 2.选择数据库: use test 3.查看数据库中有哪些集合: show collections 如下图: 查询 1.查看集合中有哪些数据,其中abc为 ...
- 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 ...
随机推荐
- Unix系统编程()文件控制操作fcntl
fcntl系统调用对一个打开的文件描述符执行一系列的控制操作. int fcntl(int fd, int cmd, -) cmd参数所支持的操作范围很广 fcntl的第三个参数以省略号表示,意味着可 ...
- 【BZOJ】1657: [Usaco2006 Mar]Mooo 奶牛的歌声(单调栈)
http://www.lydsy.com/JudgeOnline/problem.php?id=1657 这一题一开始我想到了nlog^2n的做法...显然可做,但是麻烦.(就是二分+rmq) 然后我 ...
- Android SDK代理server解决国内不能更新下载问题
读者须知:本篇文章中最靠谱的是第三种方式,近期有读者反映第三种方式也不行了,以下提供一点其它途径的开源镜像网站: 国内高校的开源镜像站 中国科学技术大学(debian.ustc.edu.cn) 上海交 ...
- Android的Parcelable中describeContents方法的作用
这个方法返回的值通常为0,那什么情况下需要填写其他值呢? 这个方法到目前为止返回其他唯一有效的值就是CONTENTS_FILE_DESCRIPTOR(0x01),指明这个Parcel的内容包含文件描述 ...
- hdu 2527:Safe Or Unsafe(数据结构,哈夫曼树,求WPL)
Safe Or Unsafe Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)To ...
- v8随心记
因为node原因,研究v8已经有段时间了,但是一直也没有抽空写点什么,现在想想有好多当时清晰的东西又模糊了.哎,伤心的很啊.但是一时又想不起什么章法,所以只能随手胡乱写了. 下载.编译: https: ...
- ios开发之 -- 单例类
单例模式是一种软件设计模式,再它的核心结构中指包含一个被称为单例类的特殊类. 通过单例模式可以保证系统中一个类只有一个势力而且该势力易于外界访问,从而方便对势力个数的控制并节约系统资源.如果希望在系统 ...
- iOS开发之 -- bundle程序束的制造
我们在写项目的时候,需要添加大量的图片,这个时候除了在x-code-->Assets文件里面添加图片外,还可以添加程序束,这样的话 项目看起来比较整齐,也显得比较专业,下面就来说一下程序束的制造 ...
- 《C++ Primer Plus》第8章 函数探幽 学习笔记
C++ 扩展了 C 语言的函数功能.通过将 inline 关键字用于函数定义,并在首次调用该函数前提供其函数定义,可以使得 C++ 编译器将该函数视为内联函数.也就是说,编译器不是让程序跳到独立的代码 ...
- 简单深搜:POJ1546——Sum it up
结束了三分搜索的旅程 我开始迈入深搜的大坑.. 首先是一道比较基础的深搜题目(还是很难理解好么) POJ 1564 SUM IT UP 大体上的思路无非是通过深搜来进行穷举.匹配 为了能更好地理解深搜 ...