Để giới hạn tăng giá trị chỉ áp dụng cho các tài liệu thỏa mãn điều kiện (ví dụ: điểm < 75), dùng truy vấn có điều kiện trong update():
db.yourCollectionName.update(
{ yourFieldName: { $lt: yourValue } },
{ $inc: { yourFieldName: yourIncrementValue } },
false, true
);
Tạo collection
> db.limitIncrementDemo.insertOne({"StudentId":101,"StudentScore":95});
{ "acknowledged": true, "insertedId": ObjectId("5cd2ce9eb64f4b851c3a13c3") }
> db.limitIncrementDemo.insertOne({"StudentId":102,"StudentScore":55});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea0b64f4b851c3a13c4") }
> db.limitIncrementDemo.insertOne({"StudentId":103,"StudentScore":67});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea1b64f4b851c3a13c5") }
> db.limitIncrementDemo.insertOne({"StudentId":104,"StudentScore":56});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea3b64f4b851c3a13c6") }
> db.limitIncrementDemo.insertOne({"StudentId":105,"StudentScore":79});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea4b64f4b851c3a13c7") }
Hiển thị tất cả
> db.limitIncrementDemo.find().pretty();
Tăng 10 điểm cho sinh viên có điểm < 75
> db.limitIncrementDemo.update(
{ StudentScore: { $lt: 75 } },
{ $inc: { StudentScore: 10 } },
false, true
);
WriteResult({ "nMatched": 3, "nUpserted": 0, "nModified": 3 })
Kết quả
> db.limitIncrementDemo.find().pretty();
Kết quả (3 tài liệu điểm < 75 đã tăng 10):
{
"_id": ObjectId("5cd2ce9eb64f4b851c3a13c3"), "StudentId": 101, "StudentScore": 95
}
{
"_id": ObjectId("5cd2cea0b64f4b851c3a13c4"), "StudentId": 102, "StudentScore": 65
}
{
"_id": ObjectId("5cd2cea1b64f4b851c3a13c5"), "StudentId": 103, "StudentScore": 77
}
{
"_id": ObjectId("5cd2cea3b64f4b851c3a13c6"), "StudentId": 104, "StudentScore": 66
}
{
"_id": ObjectId("5cd2cea4b64f4b851c3a13c7"), "StudentId": 105, "StudentScore": 79
}
Lưu ý: Tham số thứ 3 false = không upsert, tham số thứ 4 true = multi-update (cập nhật nhiều tài liệu). Phiên bản mới dùng updateMany().