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

Cách thay thế chuỗi con trong document MongoDB

Sử dụng hàm replace() của JavaScript trong phương thức forEach() để thay thế chuỗi con trong document MongoDB.

Ví dụ minh họa

Tạo collection replaceSubstringDemo với URL bị sai chính tả:

> db.replaceSubstringDemo.insertOne({"WebsiteURL": "www.gogle.com"});

Truy vấn thay thế

> db.replaceSubstringDemo.find({WebsiteURL: "www.gogle.com"}).forEach(function(url) {
  url.WebsiteURL = url.WebsiteURL.replace("www.gogle.com", "www.google.com");
  db.replaceSubstringDemo.save(url);
});

Kiểm tra kết quả:

> db.replaceSubstringDemo.find().pretty();
{ "_id": ObjectId("..."), "WebsiteURL": "www.google.com" }

Lưu ý: Cách này phù hợp cho cập nhật một lần (one-time update). Với MongoDB 4.2+, có thể dùng updateMany() với pipeline aggregation sử dụng $replaceOne hoặc $replaceAll hiệu quả hơn.