在mongo shell中,读操做的主要方法是db.collection.find(),该方法查询一个集合并一个包含返回文档的游标。一般经过遍历游标的方式,访问游标中的文档。若是返回的游标未赋值给一个变量(var keyword)那么这个游标自动遍历20次以显示前20个结果,而后等待请求遍历剩余的结果。在shell中,用"it"遍历下一个结果集。 shell
经过调用该游标变量迭代20次并打印出匹配的文档: json
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 }
查看游标函数: spa
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];两种方式均可以。