Vấn đề
Cần cập nhật trường chỉ khi giá trị mới lớn hơn giá trị hiện tại (conditional update), hoặc upsert nếu document chưa tồn tại.
Giải pháp: Toán tử $max
Toán tử $max chỉ cập nhật trường nếu giá trị chỉ định lớn hơn giá trị hiện tại. Nếu trường không tồn tại, $max sẽ tạo trường mới với giá trị đó (tương tự upsert khi kết hợp với upsert: true).
Ví dụ minh họa
1. Tạo collection và dữ liệu
> db.conditionalUpdatesDemo.insertOne({"_id":100,"StudentFirstScore":89,"StudentSecondScore":78,"BiggestScore":89});
> db.conditionalUpdatesDemo.insertOne({"_id":101,"StudentFirstScore":305,"StudentSecondScore":560,"BiggestScore":1050});
> db.conditionalUpdatesDemo.insertOne({"_id":103,"StudentFirstScore":560,"StudentSecondScore":789,"BiggestScore":880});
2. Xem dữ liệu ban đầu
> db.conditionalUpdatesDemo.find().pretty();
3. Cập nhật có điều kiện với $max
> db.conditionalUpdatesDemo.update(
{_id: 100},
{$max: {"BiggestScore": 150}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Giá trị BiggestScore của _id=100 từ 89 → 150 (vì 150 > 89).
4. Thử cập nhật với giá trị nhỏ hơn
> db.conditionalUpdatesDemo.update(
{_id: 100},
{$max: {"BiggestScore": 100}}
);
Không thay đổi vì 100 < 150 (giá trị hiện tại).
5. Upsert có điều kiện
> db.conditionalUpdatesDemo.update(
{_id: 105},
{$max: {"BiggestScore": 200}},
{upsert: true}
);
Tạo document mới _id=105 với BiggestScore=200.
Các toán tử điều kiện tương tự
$min: chỉ cập nhật nếu giá trị mới nhỏ hơn hiện tại.$setOnInsert: chỉ set giá trị khi upsert tạo document mới.