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

วิธีอัปเดตค่าเป็นตัวพิมพ์เล็ก (Lowercase) ใน MongoDB ด้วย forEach และ toLowerCase()

MongoDB มี operator $toLower ใน Aggregation แต่สำหรับ Update จริง ต้องใช้ forEach() วนลูปอัปเดตทีละเอกสาร (หรือใช้ Aggregation Pipeline ใน MongoDB 4.2+)

วิธีที่ 1: forEach + toLowerCase() (Classic Shell)

1. สร้างข้อมูลตัวอย่าง

> db.toLowerDemo.insertOne({"StudentId":101,"StudentName":"John"});
> db.toLowerDemo.insertOne({"StudentId":102,"StudentName":"Larry"});
> db.toLowerDemo.insertOne({"StudentId":103,"StudentName":"CHris"});
> db.toLowerDemo.insertOne({"StudentId":104,"StudentName":"ROBERT"});

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

> db.toLowerDemo.find().pretty();
{ "_id" : ..., "StudentId" : 101, "StudentName" : "John" }
{ "_id" : ..., "StudentId" : 102, "StudentName" : "Larry" }
{ "_id" : ..., "StudentId" : 103, "StudentName" : "CHris" }
{ "_id" : ..., "StudentId" : 104, "StudentName" : "ROBERT" }

3. วนลูปอัปเดตเป็น Lowercase

> db.toLowerDemo.find().forEach(function(doc) {
    doc.StudentName = doc.StudentName.toLowerCase();
    db.toLowerDemo.save(doc);
});

4. ผลลัพธ์

> db.toLowerDemo.find().pretty();
{ "_id" : ..., "StudentId" : 101, "StudentName" : "john" }
{ "_id" : ..., "StudentId" : 102, "StudentName" : "larry" }
{ "_id" : ..., "StudentId" : 103, "StudentName" : "chris" }
{ "_id" : ..., "StudentId" : 104, "StudentName" : "robert" }

วิธีที่ 2: Aggregation Pipeline Update (MongoDB 4.2+)

db.toLowerDemo.updateMany(
    {},
    [ { $set: { StudentName: { $toLower: "$StudentName" } } } ]
);

วิธีนี้ Atomic, เร็วกว่า, และรันได้ใน Single Command

วิธีที่ 3: $toLower ใน Aggregation (Read-only)

db.toLowerDemo.aggregate([
    { $project: { 
        StudentId: 1, 
        StudentNameLower: { $toLower: "$StudentName" } 
    }}
]);

เปรียบเทียบ

วิธีVersionเขียน DBความเร็วAtomic
forEach + save()AllYesช้า (Round-trip ต่อ Doc)ต่อ Doc
updateMany + [$set, $toLower]4.2+Yesเร็ว (Server-side)Yes
aggregate + $toLowerAllNo (Read only)เร็วN/A

สรุป

  • MongoDB 4.2+: ใช้ updateMany({}, [{ $set: { field: { $toLower: "$field" } }}])
  • MongoDB < 4.2: ใช้ forEach() + toLowerCase() + save()
  • $toLower ใน Aggregation ใช้สำหรับ Read/Transform ได้ทุก Version
  • ควร Backup ก่อน Update ทั่ว Collection