Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cập nhật collection MongoDB dùng $toLower (chuyển chữ thường)

Giới thiệu

MongoDB cung cấp toán tử $toLower dùng trong framework aggregation (tổng hợp). Tuy nhiên cũng có thể dùng vòng lặp forEach để duyệt qua trường cụ thể và cập nhật từng document một.

Ví dụ minh họa

1. Tạo collection và dữ liệu mẫu

> db.toLowerDemo.insertOne({"StudentId":101,"StudentName":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9b1b4515e86fd1496b38bf") }
> db.toLowerDemo.insertOne({"StudentId":102,"StudentName":"Larry"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9b1b4b15e86fd1496b38c0") }
> db.toLowerDemo.insertOne({"StudentId":103,"StudentName":"CHris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9b1b5115e86fd1496b38c1") }
> db.toLowerDemo.insertOne({"StudentId":104,"StudentName":"ROBERT"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9b1b5a15e86fd1496b38c2") }

2. Xem dữ liệu ban đầu

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

Kết quả: StudentName có chữ hoa/thường lẫn lộn (John, Larry, CHris, ROBERT).

3. Cập nhật dùng forEach + toLowerCase()

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

4. Kết quả sau cập nhật

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

Kết quả: tất cả StudentName chuyển thành chữ thường (john, larry, chris, robert).

Lưu ý

Phương pháp forEach + toLowerCase() (JavaScript) hoạt động tốt cho tập dữ liệu nhỏ/vừa. Với dữ liệu lớn, nên dùng $toLower trong aggregation pipeline kết hợp updateMany hoặc bulkWrite để hiệu quả hơn.