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

Giảm giá trị đơn lẻ trong MongoDB

Để giảm giá trị của một trường số cho một tài liệu cụ thể, MongoDB sử dụng toán tử $inc với giá trị âm. Kết hợp với điều kiện $gt trong query để đảm bảo không giảm dưới 0 (nếu cần).

Tạo dữ liệu mẫu

> db.decrementingOperationDemo.insertOne({"ProductName":"Product-1","ProductPrice":756});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7a8ae6d78f205348bc63c") }
> db.decrementingOperationDemo.insertOne({"ProductName":"Product-2","ProductPrice":890});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7a8b86d78f205348bc63d") }
> db.decrementingOperationDemo.insertOne({"ProductName":"Product-3","ProductPrice":994});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7a8c66d78f205348bc63e") }
> db.decrementingOperationDemo.insertOne({"ProductName":"Product-4","ProductPrice":1000});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7a8d06d78f205348bc63f") }

Xem dữ liệu

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

Giảm 10 đơn vị cho Product-4 (có điều kiện giá > 0)

> db.decrementingOperationDemo.update(
  {_id: ObjectId("5cd7a8d06d78f205348bc63f"), ProductPrice: {$gt: 0}}, 
  {$inc: {ProductPrice: -10}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kết quả

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

Giải thích

  • $inc: {ProductPrice: -10}: Tăng -10 (tức giảm 10) cho trường ProductPrice
  • ProductPrice: {$gt: 0} trong query: Chỉ cập nhật nếu giá hiện tại > 0 (tránh giá âm)
  • Kết hợp _id + điều kiện giá → an toàn, tránh race condition

Các toán tử cập nhật số học

Toán tửChức năngVí dụ
$incTăng/giảm giá trị{$inc: {qty: -1}}
$mulNhân giá trị{$mul: {price: 0.9}} (giảm 10%)
$minCập nhật nếu giá trị mới nhỏ hơn{$min: {lowScore: 50}}
$maxCập nhật nếu giá trị mới lớn hơn{$max: {highScore: 1000}}

Cập nhật nhiều tài liệu cùng lúc

 với positional $