Docs 菜单
Docs 主页
/ /

原子性和事务

In MongoDB, write operations are atomic on the single-document level, even if modifying multiple values. For parallel updates, each command ensures the query condition still matches.

To prevent conflicts during concurrent updates, include the expected current value in the update filter.

考虑包含此文档的集合:

db.games.insertOne( { _id: 1, score: 80 } )

这些更新操作会同时发生:

// Update A
db.games.updateOne(
{ score: 80 },
{
$set: { score: 90 }
}
)
// Update B
db.games.updateOne(
{ score: 80 },
{
$set: { score: 100 }
}
)

One update sets score to 90 or 100. The second update then fails to match { score: 80 } and does not run.

警告

Filtering on a field you do not update can cause unexpected results during concurrent updates. Consider these operations:

// Update A
db.games.updateOne(
{ _id: 1 },
{
$set: { score: 90 }
}
)
// Update B
db.games.updateOne(
{ _id: 1 },
{
$set: { score: 100 }
}
)

Both updates match { _id: 1 }, so both run. The second update overwrites the first. The first client receives no warning that its update was lost.

To avoid conflicts when filtering on non-updated fields, use $inc.

For example, consider the following concurrent update operations:

// Update A
db.games.updateOne(
{ _id: 1 },
{
$inc: { score: 10 }
}
)
// Update B
db.games.updateOne(
{ _id: 1 },
{
$inc: { score: 20 }
}
)

Both updates match { _id: 1 }. Because they increment rather than set the value, they do not overwrite each other. The final score is 110.

提示

Store Unique Values

To enforce uniqueness, create a unique index. This prevents duplicate data in inserts and updates. You can also create unique indexes on multiple fields. See Create a Single-Field Unique Index.

This section describes additional details for multi-document transactions.

当单个写操作(例如 db.collection.updateMany())修改了多份文档,则每份文档的修改都是原子性的,但整个操作不是原子性的。

在执行多文档写入操作时,无论是通过单次写入操作还是多次写入操作,其他操作都可能会交错进行。

对于需要对多个文档(在单个或多个集合中)原子性读取和写入的情况,MongoDB 支持分布式事务,包括副本集和分片集群上的事务。

有关详细信息,请参阅事务。

重要

在大多数情况下,与单文档写入操作相比,分布式事务会产生更高的性能成本,并且分布式事务的可用性不应取代有效的模式设计。在许多情况下,非规范化数据模型(嵌入式文档和数组)仍然是数据和使用案例的最佳选择。换言之,对于许多场景,适当的数据建模将最大限度地减少对分布式事务的需求。

有关其他事务使用注意事项(如运行时间限制和 oplog 大小限制),另请参阅生产注意事项

读取隔离性、一致性和新近度

后退

MongoDB CRUD 概念

在此页面上