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

Tăng giá trị (Increment) trong object lồng nhau (nested object) MongoDB với $inc

Để tăng giá trị của field bên trong object lồng nhau (hoặc object trong mảng), dùng toán tử $inc kết hợp **dot notation** và **positional operator $** (khi object nằm trong mảng).

Ví dụ minh họa

Tạo collection incrementValueDemo với object lồng trong mảng StudentDetails:

> db.incrementValueDemo.insertOne({
    "StudentName": "Larry",
    "StudentCountryName": "US",
    "StudentDetails": [
        { "StudentSubjectName": "Math", "StudentMathMarks": 79 }
    ]
});

Hiển thị:

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

Kết quả:

{
    "_id" : ObjectId("..."),
    "StudentName" : "Larry",
    "StudentCountryName" : "US",
    "StudentDetails" : [
        { "StudentSubjectName" : "Math", "StudentMathMarks" : 79 }
    ]
}

Tăng StudentMathMarks lên 1 (tìm bằng SubjectName)

> db.incrementValueDemo.update(
    { "StudentDetails.StudentSubjectName": "Math" },
    { $inc: { "StudentDetails.$.StudentMathMarks": 1 } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
  • StudentDetails.StudentSubjectName: Tìm document có phần tử trong mảng thỏa mãn.
  • $ (positional operator): Tham chiếu đến **phần tử đầu tiên** khớp trong mảng.
  • StudentDetails.$.StudentMathMarks: Đường dẫn đến field cần tăng.

Kiểm tra kết quả

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

Kết quả: Marks từ 79 -> 80.

{
    "_id" : ObjectId("..."),
    "StudentName" : "Larry",
    "StudentCountryName" : "US",
    "StudentDetails" : [
        { "StudentSubjectName" : "Math", "StudentMathMarks" : 80 }
    ]
}

Các trường hợp mở rộng

1. Object lồng trực tiếp (không phải mảng)

// Document: { "stats": { "views": 100 } }
db.coll.update({}, { $inc: { "stats.views": 1 } }); // Không cần $

2. Tăng nhiều field cùng lúc

db.coll.update(
    { "items.productId": 123 },
    { $inc: { "items.$.quantity": 1, "items.$.total": 100 } }
);

3. Tăng với điều kiện (MongoDB 5.0+): $inc trong pipeline update

db.coll.updateOne(
    { _id: id },
    [{ $set: { "items.$[elem].qty": { $add: ["$items.$[elem].qty", 1] } } }],
    { arrayFilters: [{ "elem.productId": 123 }] }
);

Lưu ý

  • $ chỉ cập nhật **phần tử đầu tiên** khớp trong mảng. Nếu cần cập nhật nhiều phần tử, dùng arrayFilters với $[] (MongoDB 3.6+).
  • $inc chấp nhận số âm để giảm giá trị.
  • Field phải là kiểu số (int, long, double). Nếu field không tồn tại, $inc sẽ tạo mới với giá trị = increment value.