บทความนี้สาธิตวิธีใช้ forEach() ร่วมกับ find() เพื่อวนลูปผ่านเอกสารและพิมพ์ค่าของฟิลด์ที่ต้องการใน MongoDB Shell
สร้างข้อมูลตัวอย่าง
> db.printDocuementValueDemo.insertOne({"InstructorName":"John Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd6804f7924bb85b3f48950") }
> db.printDocuementValueDemo.insertOne({"InstructorName":"Sam Williams"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd680577924bb85b3f48951") }
> db.printDocuementValueDemo.insertOne({"InstructorName":"David Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd680637924bb85b3f48952") }
แสดงข้อมูลทั้งหมด
> db.printDocuementValueDemo.find().pretty();
{
"_id" : ObjectId("5cd6804f7924bb85b3f48950"),
"InstructorName" : "John Smith"
}
{
"_id" : ObjectId("5cd680577924bb85b3f48951"),
"InstructorName" : "Sam Williams"
}
{
"_id" : ObjectId("5cd680637924bb85b3f48952"),
"InstructorName" : "David Miller"
}
พิมพ์ค่า InstructorName ของเอกสารที่ _id เฉพาะเจาะจง
> db.printDocuementValueDemo.find(
{ _id : ObjectId("5cd680577924bb85b3f48951") },
{ InstructorName: 1, _id: 0 }
).forEach(function(myDocument) {
print(myDocument.InstructorName);
});
ผลลัพธ์
Sam Williams
คำอธิบายโค้ด
find(query, projection): Query หา _id เฉพาะเจาะจง, Projection ดึงแค่ InstructorName (ไม่เอา _id)forEach(function(doc) { ... }): วนลูปแต่ละ Document ที่ Query คืนมาprint(): พิมพ์ค่าออกทาง Console ใน Mongo Shell
ตัวอย่างเพิ่มเติม: พิมพ์ทุก Document
> db.printDocuementValueDemo.find({}, { InstructorName: 1, _id: 0 })
.forEach(function(doc) { print(doc.InstructorName); });
John Smith Sam Williams David Miller
ตัวอย่าง: นำค่าที่ได้ไปประมวลผลต่อ
> db.collection.find().forEach(function(doc) {
var upperName = doc.name.toUpperCase();
db.collection.updateOne(
{ _id: doc._id },
{ $set: { "name_upper": upperName } }
);
});
หมายเหตุ
forEach() ใช้ได้เฉพาะใน Mongo Shell (JavaScript Environment) ไม่สามารถใช้ใน Driver ภาษาอื่นได้โดยตรง