Vấn đề
Cập nhật trường StudentName thành chữ thường (lowercase) cho tất cả document trong collection.
Giải pháp: Vòng lặp forEach + JavaScript toLowerCase()
MongoDB shell cho phép chạy JavaScript. Dùng find() kết hợp forEach() duyệt từng document, sửa trường, lưu lại bằng save().
Ví dụ minh họa
1. Tạo dữ liệu (StudentName có chữ hoa/thường lẫn lộn)
> db.lowerCaseDemo.insertOne({"StudentName":"JOHN SMith"});
> db.lowerCaseDemo.insertOne({"StudentName":"CAROL TAYLor"});
> db.lowerCaseDemo.insertOne({"StudentName":"DAVID Miller"});
2. Xem dữ liệu ban đầu
> db.lowerCaseDemo.find().pretty();
3. Cập nhật lowercase
> db.lowerCaseDemo.find({StudentName: {$exists: true}}).forEach(
function(v) {
v.StudentName = v.StudentName.toLowerCase();
db.lowerCaseDemo.save(v);
}
);
{StudentName: {$exists: true}} chỉ lấy document có trường StudentName (tránh lỗi null).
4. Kết quả
> db.lowerCaseDemo.find().pretty();
{ "_id" : ..., "StudentName" : "john smith" }
{ "_id" : ..., "StudentName" : "carol taylor" }
{ "_id" : ..., "StudentName" : "david miller" }
Phương pháp thay thế (MongoDB 3.4+): $toLower trong aggregation + updateMany
db.lowerCaseDemo.updateMany(
{},
[{$set: {StudentName: {$toLower: "$StudentName"}}}]
);
Cách này hiệu quả hơn, atomic, không cần vòng lặp JavaScript.