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

Cách cập nhật chỉ các trường cụ thể trong MongoDB

Giới thiệu

Để cập nhật (update) chỉ một hoặc vài trường cụ thể mà không ảnh hưởng đến các trường khác, bạn sử dụng toán tử $set trong update operation.

Cú pháp

// Cập nhật một trường
db.collection.updateOne(
    { filter },
    { $set: { tenTruong: giaTriMoi } }
);

// Cập nhật nhiều trường cùng lúc
db.collection.updateOne(
    { filter },
    { $set: { truong1: giaTri1, truong2: giaTri2, ... } }
);

Ví dụ minh họa

1. Tạo collection nhân viên

> db.capNhatTruong.insertOne({ "TenNhanVien": "John", "QuocGia": "UK" });
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ea849d628fa4220163b72") }
> db.capNhatTruong.insertOne({ "TenNhanVien": "Larry", "QuocGia": "US" });
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ea853d628fa4220163b73") }
> db.capNhatTruong.insertOne({ "TenNhanVien": "David", "QuocGia": "AUS" });
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ea85bd628fa4220163b74") }

2. Cập nhật TenNhanVien từ "John" thành "Robert" (chỉ trường này)

> db.capNhatTruong.updateOne(
    { _id: ObjectId("5c9ea849d628fa4220163b72") },
    { $set: { "TenNhanVien": "Robert" } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

3. Kết quả - QuocGia vẫn giữ nguyên "UK"

> db.capNhatTruong.find().pretty();
{ "_id" : ObjectId("5c9ea849d628fa4220163b72"), "TenNhanVien" : "Robert", "QuocGia" : "UK" }
{ "_id" : ObjectId("5c9ea853d628fa4220163b73"), "TenNhanVien" : "Larry", "QuocGia" : "US" }
{ "_id" : ObjectId("5c9ea85bd628fa4220163b74"), "TenNhanVien" : "David", "QuocGia" : "AUS" }

Các toán tử update hữu ích khác

Toán tửChức năngVí dụ
$setGán giá trị mới (tạo mới nếu chưa có){ $set: { age: 25 } }
$unsetXóa trường{ $unset: { oldField: "" } }
$incTăng/giảm giá trị số{ $inc: { count: 1 } }
$mulNhân giá trị số{ $mul: { price: 1.1 } }
$renameĐổi tên trường{ $rename: { "oldName": "newName" } }
$setOnInsertChỉ set khi upsert tạo mới{ $setOnInsert: { createdAt: new Date() } }
$currentDateSet giá trị ngày giờ hiện tại{ $currentDate: { lastModified: true } }

Update nhiều document (updateMany)

// Cập nhật QuocGia = "VN" cho tất cả nhân viên tên "John"
db.capNhatTruong.updateMany(
    { TenNhanVien: "John" },
    { $set: { QuocGia: "VN" } }
);

Pipeline Update (MongoDB 4.2+)

Cho phép dùng aggregation expression trong update:

// Tăng lương 10% và cập nhật lastModified
db.nhanVien.updateMany(
    { phongBan: "IT" },
    [
        { $set: { 
            luong: { $multiply: ["$luong", 1.1] },
            lastModified: "$$NOW"
        } }
    ]
);

Lưu ý quan trọng

  • KHÔNG** dùng update() không có $set (sẽ replace toàn bộ document!)
  • Sai: db.coll.update({_id: id}, { name: "New" }) → Mất hết field khác
  • Đúng: db.coll.updateOne({_id: id}, { $set: { name: "New" } })
  • Luôn dùng updateOne hoặc updateMany thay vì update (deprecated)