Nâng CaoMongoDB iconMongoDB

Optimistic concurrency trong MongoDB làm thế nào?

Optimistic concurrency dùng version field hoặc updatedAt trong filter update. Nếu document đã bị update bởi request khác, update count bằng 0 và app báo conflict/retry.

Ví dụ:

javascript
const result = await users.updateOne(
  { _id, version },
  { $set: changes, $inc: { version: 1 } }
)
if (result.matchedCount === 0) throw new Error("Conflict")

Pattern này hữu ích cho edit form, inventory nhẹ hoặc aggregate update không muốn lock lâu.

Xem toàn bộ MongoDB cùng filter theo level & chủ đề con.

Mở danh sách MongoDB