MongoDB学习笔记--游标(Cursor)(四)


  • 游标的使用

      在mongo shell中,读操作的主要方法是db.collection.find(),该方法查询一个集合并一个包含返回文档的游标。通常通过遍历游标的方式,访问游标中的文档。如果返回的游标未赋值给一个变量(var keyword)那么这个游标自动遍历20次以显示前20个结果,然后等待请求遍历剩余的结果。在shell中,用"it"遍历下一个结果集。

  • 手动迭代游标

      通过调用该游标变量迭代20次并打印出匹配的文档:

var myCurrsor = db.testData.find();
myCursor
          可通过next()方法访问文档:   

var myCursor = db.testData.find();
var myDocument = myCursor.hasNext() ? myCursor.next() : null;

if (myDocument) {
    var myItem = myDocument.item;
    print(tojson(myItem));
}
         打印的别一个方式:

if (myDocument) {
    var myItem = myDocument.item;
    printjson(myItem);
}
         通过forEach()
var myCursor =  db.testData.find();
myCursor.forEach(printjson);

显示结果:

{ "_id" : ObjectId("51a7dc7b2cacf40b79990be6"), "x" : 1 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be7"), "x" : 2 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be8"), "x" : 3 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be9"), "x" : 4 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bea"), "x" : 5 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990beb"), "x" : 6 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bec"), "x" : 7 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bed"), "x" : 8 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bee"), "x" : 9 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bef"), "x" : 10 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf0"), "x" : 11 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf1"), "x" : 12 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf2"), "x" : 13 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf3"), "x" : 14 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf4"), "x" : 15 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf5"), "x" : 16 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf6"), "x" : 17 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf7"), "x" : 18 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf8"), "x" : 19 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf9"), "x" : 20 }

     查看游标函数:

c.help()


  • 返回一个文档
db.testData.findOne()
  • 返回限定文档条(记录)数的结果集
db.testData.find().limit(5)


  • 索引迭代  

var myCursor = db.testData.find();
var documentArray = myCursor.toArray();
var myDocument = documentArray[3];

var myCursor = db.testData.find();
var myDocument = myCursor[3];
    两种方式都可以。


转载于:https://my.oschina.net/u/990629/blog/169239

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值