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() | All | Yes | ช้า (Round-trip ต่อ Doc) | ต่อ Doc |
| updateMany + [$set, $toLower] | 4.2+ | Yes | เร็ว (Server-side) | Yes |
| aggregate + $toLower | All | No (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