mongodb05---游标

游标cursor:

通俗的说,游标不是查询结果,而是查询的返回资源,或者接口.
通过这个接口,你可以逐条读取.就像php中的fopen打开文件,得到一个资源一样, 通过资源,可以一行一行的读文件.

var cursor1 =  db.bar.find({});  //10000条没有输出,

db.bar.find().count();
var cursor1 =  db.bar.find({_id:{$lte:10}});//id小于等于10
while(cursor1.hasNext()){   //while循环
    print(cursor1.next());//打印bson,next一次就移动一次
    printjson(cursor1.next());//next一次就移动一次
}

//for循环输出
for(var cs=db.bar.find({_id:{$lte:10}}),doc=true;cs.hasNext();){
    printjson(cs.next());
}

//foreach输出:
var cs = db.bar.find({_id:{$lte:10}});
cs.forEach(function(o){printjson('你的title是'+o.title)})
输出:
"你的title是hello1"
"你的title是hello3"
"你的title是hello5"
"你的title是hello7"
"你的title是hello9"
"你的title是hello11"




游标在分页中的应用
比如查到10000行,跳过100页,取10行.一般地,我们假设每页N行, 当前是page页就需要跳过前 (page-1)*N 行, 再取N行,
 
在mysql中, limit offset,N来实现
在mongo中,用skip(), limit()函数来实现的

如 var mycursor = db.bar.find().skip(9995);
则是查询结果中,跳过前9995行
查询第901页,每页10条
则是 
var mycursor = db.bar.find().skip(500).limit(10);
mycursor.forEach(function(o){printjson('你的title是'+o.title)});




通过cursor一次性得到所有数据, 并返回数组.
例:
var cursor = db.bar.find().skip(500).limit(20);
printjson(cursor.toArray());  //不想迭代,而是直接打印出来,看到所有行
printjson(cursor.toArray()[2]);  //看到第2行

注意: 不要随意使用toArray()
原因: 会把所有的行立即以对象形式组织在内存里.
可以在取出少数几行时,用此功能.
</pre>
原文地址:https://www.cnblogs.com/yaowen/p/8149292.html