为了营造大批量数据,我们可以这样写javascript脚本
for (var i=1;i<=10000;i++)
{
if(i%2==1)
{
db.cursortest.insert({_id:i,name:'程劲'+i,age:19,major:['泰拳','散打','巴西柔术','和saintding大哥玩SM']});
}
else if(i%2==0)
{
db.cursortest.insert({_id:i,name:'陈培昌'+i,age:21,major:['泰拳','散打','巴西柔术','和saintding大哥一起厮混']});
}
}
显然,这样海量的数据,需要cursor帮助我们完成查询
可以指定只显示前10行
var mycursor = db.cursortest.find({_id:{$lte:10}})
mycursor.next()依次取下一条
当然mongodb为我们封装了forEach函数来循环打印结果注意大小写:
mycursor.forEach(function(obj){printjson(obj)})
效果如下:
还有分页的功能:
var duwa = db.cursortest.find().skip(9990)
duwa.forEach(function(obj){printjson(obj)})
1 var tianwadi = db.cursortest.find().skip(9990).limit(5)
2 tianwadi.forEach(function(obj){printjson(obj)})
跨过前9990行,只显示5条
下面使用游标的toArray()方法,结果卧操~
注意!无论在命令行还是类似studio3T这样的IDE,在每次执行完游标的操作后,游标已经穷尽了数据集,所以要通过再声明一次游标的方法,以确保游标的forEach操作能继续进行。
var tianwadi = db.cursortest.find().skip(9990).limit(5)
tianwadi.toArray()
输出结果会返回一个列表,如下:
[
{
"_id" : 9991,
"name" : "程劲9991",
"age" : 19,
"major" : [
"泰拳",
"散打",
"巴西柔术",
"和丁大哥玩SM"
]
},
{
"_id" : 9992,
"name" : "陈培昌9992",
"age" : 21,
"major" : [
"泰拳",
"散打",
"巴西柔术",
"和丁大哥一起厮混"
]
},
{
"_id" : 9993,
"name" : "程劲9993",
"age" : 19,
"major" : [
"泰拳",
"散打",
"巴西柔术",
"和丁大哥玩SM"
]
},
{
"_id" : 9994,
"name" : "陈培昌9994",
"age" : 21,
"major" : [
"泰拳",
"散打",
"巴西柔术",
"和丁大哥一起厮混"
]
},
{
"_id" : 9995,
"name" : "程劲9995",
"age" : 19,
"major" : [
"泰拳",
"散打",
"巴西柔术",
"和丁大哥玩SM"
]
}
]
如果只取列表中的第4条操作如下:
var tianwadi = db.cursortest.find().skip(9990).limit(5)
tianwadi.toArray()[4]
返回结果如下;
{
"_id" : 9995,
"name" : "程劲9995",
"age" : 19,
"major" : [
"泰拳",
"散打",
"巴西柔术",
"和丁大哥玩SM"
]
}