การวนลูปผ่านคอลเลกชันด้วย Cursor ใน MongoDB
เมื่อต้องการวนลูปผ่านเอกสารในคอลเลกชัน MongoDB โดยใช้ cursor สามารถใช้รูปแบบโค้ดดังต่อไปนี้:
ไวยากรณ์พื้นฐาน
var anyVariableName1;
var anyVariableName2 = db.yourCollectionName.find();
while(yourVariableName2.hasNext()) {
yourVariableName1 = yourVariableName2.next();
printjson(yourVariableName1);
};
ตัวอย่างการสร้างคอลเลกชันและเพิ่มข้อมูล
> db.loopThroughCollectionDemo.insertOne({"StudentName":"John","StudentAge":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca81f2d6669774125247f") }
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca8272d66697741252480") }
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Chris","StudentAge":25});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca8462d66697741252481") }
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Robert","StudentAge":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca8632d66697741252482") }
แสดงข้อมูลทั้งหมดด้วย find()
> db.loopThroughCollectionDemo.find().pretty();
ผลลัพธ์:
{ "_id" : ObjectId("5c9ca81f2d6669774125247f"), "StudentName" : "John", "StudentAge" : 23 }
{ "_id" : ObjectId("5c9ca8272d66697741252480"), "StudentName" : "Larry", "StudentAge" : 21 }
{ "_id" : ObjectId("5c9ca8462d66697741252481"), "StudentName" : "Chris", "StudentAge" : 25 }
{ "_id" : ObjectId("5c9ca8632d66697741252482"), "StudentName" : "Robert", "StudentAge" : 24 }
การวนลูปด้วย Cursor
> var allDocumentValue;
> var collectionName = db.loopThroughCollectionDemo.find();
> while(collectionName.hasNext()){
allDocumentValue = collectionName.next();
printjson(allDocumentValue);
}
ผลลัพธ์:
{ "_id" : ObjectId("5c9ca81f2d6669774125247f"), "StudentName" : "John", "StudentAge" : 23 }
{ "_id" : ObjectId("5c9ca8272d66697741252480"), "StudentName" : "Larry", "StudentAge" : 21 }
{ "_id" : ObjectId("5c9ca8462d66697741252481"), "StudentName" : "Chris", "StudentAge" : 25 }
{ "_id" : ObjectId("5c9ca8632d66697741252482"), "StudentName" : "Robert", "StudentAge" : 24 }
คำอธิบายเพิ่มเติม
- find() คืนค่าเป็น cursor ซึ่งช่วยให้สามารถวนลูปผ่านผลลัพธ์ได้ทีละเอกสาร
- hasNext() ตรวจสอบว่ายังมีเอกสารถัดไปหรือไม่
- next() ดึงเอกสารถัดไปจาก cursor
- printjson() แสดงข้อมูลในรูปแบบ JSON ที่อ่านง่าย
หมายเหตุ: ใน MongoDB เวอร์ชันใหม่แนะนำให้ใช้ forEach() แทน while loop เพื่อความสะดวกและประสิทธิภาพที่ดีกว่า