在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];兩種方式均可以。