您的位置:首页 > 数据库 > Mongodb

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

2013-10-16 00:00 239 查看



游标的使用

在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];
两种方式都可以。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Mongo MongoDB