Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วนลูป Cursor และพิมพ์เอกสารใน MongoDB

ใช้ forEach() ร่วม printjson() วนอ่านและแสดงผล Cursor

เมธอด find() คืนค่า Cursor ซึ่งสามารถวนลูปได้ด้วย forEach() และพิมพ์แต่ละเอกสารด้วย printjson()

ตัวอย่างข้อมูล

> db.cursorDemo.insertOne({"StudentFullName":"John Smith","StudentAge":23});
> db.cursorDemo.insertOne({"StudentFullName":"John Doe","StudentAge":21});
> db.cursorDemo.insertOne({"StudentFullName":"Carol Taylor","StudentAge":20});
> db.cursorDemo.insertOne({"StudentFullName":"Chris Brown","StudentAge":24});

วนลูปและพิมพ์ทั้งเอกสาร

> db.cursorDemo.find().forEach(printjson);

ผลลัพธ์: พิมพ์ทุกฟิลด์ของทุกเอกสาร

วนลูปและพิมพ์เฉพาะฟิลด์ที่ต้องการ (Projection)

> db.cursorDemo.find({}, { "StudentFullName": 1, "StudentAge": 1, "_id": 0 }).forEach(printjson);

ผลลัพธ์: แสดงเฉพาะ Name และ Age

{ "StudentFullName" : "John Smith", "StudentAge" : 23 }
{ "StudentFullName" : "John Doe", "StudentAge" : 21 }
{ "StudentFullName" : "Carol Taylor", "StudentAge" : 20 }
{ "StudentFullName" : "Chris Brown", "StudentAge" : 24 }

รูปแบบการใช้งานอื่นๆ

// 1. ใช้ Function แบบเต็ม (ทำ Logic ซับซ้อนได้)
db.cursorDemo.find().forEach(function(doc) {
    if (doc.StudentAge >= 22) {
        print("Senior: " + doc.StudentFullName);
    } else {
        print("Junior: " + doc.StudentFullName);
    }
});

// 2. ใช้ for...of Loop (Modern JS, Mongo Shell 4.0+)
for (let doc of db.cursorDemo.find()) {
    printjson(doc);
}

// 3. แปลงเป็น Array ก่อน (ระวัง Memory)
var docs = db.cursorDemo.find().toArray();
docs.forEach(printjson);

ประสิทธิภาพ

  • forEach() บน Cursor: Streaming - ไม่โหลดทั้งหมดเข้าหน่วยความจำ
  • toArray(): โหลดทั้งหมด - ใช้ได้กับข้อมูลน้อย (< 10MB)
  • Projection ({ field: 1, _id: 0 }) ลด Network/IO อย่างมาก