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

Cập nhật chỉ một giá trị cụ thể trong tài liệu MongoDB

Để cập nhật chỉ một giá trị cụ thể, sử dụng update() với toán tử $set. Tạo collection:

> db.demo201.insertOne({"ClientName":"Chris Brown","ClientAge":26});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3c39ca03d395bdc21346e5") }
> db.demo201.insertOne({"ClientName":"David Miller","ClientAge":35});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3c39d403d395bdc21346e6") }
> db.demo201.insertOne({"ClientName":"Carol Taylor","ClientAge":28});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3c39e603d395bdc21346e7") }

Hiển thị tất cả tài liệu:

> db.demo201.find();

Kết quả:

Cập nhật ClientName thành "John Doe" cho tài liệu có ClientAge = 35:

> db.demo201.update({"ClientAge":35}, {$set:{"ClientName":"John Doe"}}, {multi:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kiểm tra lại:

> db.demo201.find();

Kết quả sau cập nhật:

Lưu ý: Tham số {multi: true} cập nhật tất cả tài liệu khớp. Từ MongoDB 3.2+, khuyến nghị dùng updateOne() hoặc updateMany() thay vì update().