Transactions and Operations事务和操作

On this page本页内容

For transactions:对于事务:

Operations that affect the database catalog, such as creating or dropping a collection or an index, are not allowed in multi-document transactions. 在多文档事务中,不允许执行影响数据库目录的操作,例如创建或删除集合或索引。For example, a multi-document transaction cannot include an insert operation that would result in the creation of a new collection. 例如,多文档事务不能包含导致创建新集合的插入操作。See Restricted Operations.请参阅受限操作

Operations Supported in Multi-Document Transactions多文档事务中支持的操作

CRUD OperationsCRUD操作

The following read/write operations are allowed in transactions:事务中允许以下读/写操作:

Method方法Command命令Note笔记
db.collection.aggregate()aggregate

Excluding the following stages:不包括以下阶段:

db.collection.countDocuments()

Excluding the following query operator expressions:不包括以下查询运算符表达式:

The method uses the $match aggregation stage for the query and $group aggregation stage with a $sum expression to perform the count.该方法使用$match聚合阶段进行查询,使用$group聚合阶段和$sum表达式执行计数。

db.collection.distinct()distinct

Available on unsharded collections.可用于未归档的集合。

For sharded collections, use the aggregation pipeline with the $group stage. 对于分片集合,使用聚合管道和$group阶段。See Distinct Operation.请参阅Distinct操作
db.collection.find()find
delete
findAndModify

Starting in MongoDB 4.4, if the update or replace operation is run with upsert: true on a non-existing collection, the collection is implicitly created.从MongoDB 4.4开始,如果在不存在的集合上使用upsert:true运行更新或替换操作,则会隐式创建该集合。

In MongoDB 4.2 and earlier, if upsert: true, the operation must be run on an existing collection.在MongoDB 4.2及更早版本中,如果upsert:true,则该操作必须在现有集合上运行。

Tip提示
See also: 参阅:
insert

Starting in MongoDB 4.4, if run on a non-existing collection, the collection is implicitly created.从MongoDB 4.4开始,如果在不存在的集合上运行,则隐式创建该集合。

In MongoDB 4.2 and earlier, the operation must be run on an existing collection.在MongoDB 4.2及更早版本中,该操作必须在现有集合上运行。

Tip提示
See also: 参阅:
update

Starting in MongoDB 4.4, if run on a non-existing collection, the collection is implicitly created.从MongoDB 4.4开始,如果在不存在的集合上运行,则隐式创建该集合。

In MongoDB 4.2 and earlier, the operation must be run on an existing collection.在MongoDB 4.2及更早版本中,该操作必须在现有集合上运行。

Tip提示
See also: 参阅:

Starting in MongoDB 4.4, if run on a non-existing collection, the collection is implicitly created.从MongoDB 4.4开始,如果在不存在的集合上运行,则隐式创建该集合。

In MongoDB 4.2 and earlier, the operation must be run on an existing collection.在MongoDB 4.2及更早版本中,该操作必须在现有集合上运行。

Tip提示
See also: 参阅:
Note注意
Updates to Shard Key Values更新分片键值

Starting in MongoDB 4.2, you can update a document's shard key value (unless the shard key field is the immutable _id field) by issuing single-document update/findAndModify operations either in a transaction or as a retryable write. 从MongoDB 4.2开始,您可以通过在事务或可重试写入中发出单个文档更新/查找和修改操作来更新文档的shard键值(除非分片键字段是不可变的_id字段)。For details, see Change a Document's Shard Key Value.有关详细信息,请参阅更改文档的Shard键值

Count Operation计数操作

To perform a count operation within a transaction, use the $count aggregation stage or the $group (with a $sum expression) aggregation stage.要在事务中执行计数操作,请使用$count聚合阶段或$group(带有$sum表达式)聚合阶段。

MongoDB drivers compatible with the 4.0 features provide a collection-level API countDocuments(filter, options) as a helper method that uses the $group with a $sum expression to perform a count. 与4.0功能兼容的MongoDB驱动程序提供了一个集合级API countDocuments(filter, options)作为辅助方法,使用带有$sum表达式的$group来执行计数。The 4.0 drivers have deprecated the count() API.4.0驱动程序已经弃用了count()API。

Starting in MongoDB 4.0.3, mongosh provides the db.collection.countDocuments() helper method that uses the $group with a $sum expression to perform a count.从MongoDB 4.0.3开始,mongosh提供了db.collection.countDocuments()辅助方法,该方法使用带有$sum表达式的$group来执行计数。

Distinct Operation独特的操作

To perform a distinct operation within a transaction:要在事务中执行不同的操作:

  • For unsharded collections, you can use the db.collection.distinct() method/the distinct command as well as the aggregation pipeline with the $group stage.对于未归档的集合,可以使用db.collection.distinct()方法/distinct命令以及带有$group阶段的聚合管道。
  • For sharded collections, you cannot use the db.collection.distinct() method or the distinct command.对于分片集合,不能使用db.collection.distinct()方法或distinct命令。

    To find the distinct values for a sharded collection, use the aggregation pipeline with the $group stage instead. 要查找分片集合的不同值,请将聚合管道与$group阶段一起使用。For example:例如:

    • Instead of db.coll.distinct("x"), use

      db.coll.aggregate([
         { $group: { _id: null, distinctValues: { $addToSet: "$x" } } },
         { $project: { _id: 0 } }
      ])
    • Instead of db.coll.distinct("x", { status: "A" }), use:不要使用db.coll.distinct("x", { status: "A" }),请使用:

      db.coll.aggregate([
         { $match: { status: "A" } },
         { $group: { _id: null, distinctValues: { $addToSet: "$x" } } },
         { $project: { _id: 0 } }
      ])

    The pipeline returns a cursor to a document:管道将游标返回到文档:

    { "distinctValues" : [ 2, 3, 1 ] }

    Iterate the cursor to access the results document.迭代游标以访问结果文档。

DDL OperationsDDL操作

Starting in MongoDB 4.4 with feature compatibility version (fcv) "4.4", you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.功能兼容版本(fcv)"4.4"的MongoDB 4.4开始,如果事务不是跨分片写入事务,则可以在多文档事务内创建集合和索引。

Explicit DDL Operations显式DDL操作

CommandMethod方法Notes
createdb.createCollection()See also the Implicit DDL Operations.另请参见隐式DDL操作
createIndexes The index to create must either be on a non-existing collection, in which case, the collection is created as part of the operation, or on a new empty collection created earlier in the same transaction.要创建的索引必须位于不存在的集合上,在这种情况下,该集合是作为操作的一部分创建的,或者位于同一事务中先前创建的新空集合上。
Note注意

For explicit creation of a collection or an index inside a transaction, the transaction read concern level must be "local".对于在事务内显式创建集合或索引,事务读取关注级别必须为"local"

For more information on creating collections and indexes in a transaction, see Create Collections and Indexes In a Transaction.有关在事务中创建集合和索引的更多信息,请参阅在事务中创建集合和索引

Implicit DDL Operations隐式DDL操作

You can also implicitly create a collection through the following write operations against a non-existing collection:您还可以对不存在的集合通过以下写入操作隐式创建集合:

Method Run against Non-Existing Collection方法对不存在的集合运行Command Run against Non-Existing Collection针对不存在的集合运行命令
db.collection.findAndModify() with 配合upsert: true
db.collection.findOneAndReplace() with 配合upsert: true
db.collection.findOneAndUpdate() with 配合upsert: true
findAndModify with 配合upsert: true
insert
db.collection.updateOne() with 配合upsert: true
db.collection.updateMany() with 配合upsert: true
db.collection.replaceOne() with 配合upsert: true
update with 配合upsert: true
db.collection.bulkWrite() with insert or upsert:true operations配合插入或upsert:true操作
Various Bulk Operation Methods with insert or upsert:true operations的各种批量操作方法配合insertupsert:true操作

For other CRUD operations allowed in transactions, see CRUD Operations.有关事务中允许的其他CRUD操作,请参阅CRUD操作

For more information on creating collections and indexes in a transaction, see Create Collections and Indexes In a Transaction.有关在事务中创建集合和索引的更多信息,请参阅在事务中创建集合和索引

Informational Operations信息操作

Informational commands, such as hello, buildInfo, connectionStatus (and their helper methods) are allowed in transactions; however, they cannot be the first operation in the transaction.事务中允许使用信息命令,如hellobuildInfoconnectionStatus(及其助手方法);但是,它们不能是事务中的第一个操作。

Restricted Operations受限操作

Changed in version 4.4.在版本4.4中更改

The following operations are not allowed in transactions:事务中不允许以下操作:

←  Production Considerations (Sharded Clusters)Indexes →