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

การใช้ toLowerCase() ใน forEach เพื่ออัปเดตชื่อนักเรียนใน MongoDB

ใช้เมธอด toLowerCase() ของ JavaScript ร่วมกับ forEach() เพื่อแปลงค่าฟิลด์ให้เป็นตัวพิมพ์เล็กทั้งหมดในคอลเลกชัน

ตัวอย่างข้อมูลทดสอบ (ชื่อมีตัวพิมพ์ใหญ่-เล็กสลับกัน)

> db.lowerCaseDemo.insertOne({"StudentName": "JOHN SMith"});
{ "acknowledged": true, "insertedId": ObjectId("5cd9a86fb50a6c6dd317ad9f") }
> db.lowerCaseDemo.insertOne({"StudentName": "CAROL TAYLor"});
{ "acknowledged": true, "insertedId": ObjectId("5cd9a88fb50a6c6dd317ada0") }
> db.lowerCaseDemo.insertOne({"StudentName": "DAVID Miller"});
{ "acknowledged": true, "insertedId": ObjectId("5cd9a89fb50a6c6dd317ada1") }

แสดงข้อมูลก่อนแปลง

> db.lowerCaseDemo.find().pretty();

ผลลัพธ์

{
  "_id": ObjectId("5cd9a86fb50a6c6dd317ad9f"),
  "StudentName": "JOHN SMith"
}
{
  "_id": ObjectId("5cd9a88fb50a6c6dd317ada0"),
  "StudentName": "CAROL TAYLor"
}
{
  "_id": ObjectId("5cd9a89fb50a6c6dd317ada1"),
  "StudentName": "DAVID Miller"
}

แปลงเป็นตัวพิมพ์เล็กด้วย forEach และ toLowerCase()

> db.lowerCaseDemo.find({StudentName: { $exists: true }}).forEach(
    function(v) {
      v.StudentName = v.StudentName.toLowerCase();
      db.lowerCaseDemo.save(v);
    }
  );

ตรวจสอบหลังแปลง

> db.lowerCaseDemo.find().pretty();

ผลลัพธ์ (ชื่อเป็นตัวพิมพ์เล็กทั้งหมด)

{
  "_id": ObjectId("5cd9a86fb50a6c6dd317ad9f"),
  "StudentName": "john smith"
}
{
  "_id": ObjectId("5cd9a88fb50a6c6dd317ada0"),
  "StudentName": "carol taylor"
}
{
  "_id": ObjectId("5cd9a89fb50a6c6dd317ada1"),
  "StudentName": "david miller"
}

หมายเหตุ: save() จะแทนที่เอกสารทั้งหมด สำหรับ MongoDB ใหม่ ควรใช้ updateOne() หรือ updateMany() กับ $set แทนเพื่อประสิทธิภาพที่ดีกว่า