Docs HomeMongoDB Manual

Transactions and Operations事务和操作

For transactions:对于事务:

  • You can specify read/write (CRUD) operations on existing collections. 您可以在现有集合上指定读/写(CRUD)操作。For a list of CRUD operations, see CRUD Operations.有关CRUD操作的列表,请参阅CRUD操作

  • Starting in MongoDB 4.4, you can create collections and indexes in transactions. 从MongoDB 4.4开始,您可以在事务中创建集合和索引。For details, see Create Collections and Indexes In a Transaction有关详细信息,请参阅在事务中创建集合和索引

  • The collections used in a transaction can be in different databases.事务中使用的集合可以在不同的数据库中。

    Note

    You cannot create new collections in cross-shard write transactions. 不能在跨分片写入事务中创建新集合。For example, if you write to an existing collection in one shard and implicitly create a collection in a different shard, MongoDB cannot perform both operations in the same transaction.例如,如果您在一个shard中写入一个现有集合,并在另一个shard中隐式创建一个集合,则MongoDB无法在同一事务中执行这两个操作。

  • You cannot write to capped collections. 您不能写入封顶集合(Starting in MongoDB 4.2)

  • You cannot use read concern "snapshot" when reading from a capped collection. (Starting in MongoDB 5.0)

  • You cannot read/write to collections in the config, admin, or local databases.

  • You cannot write to system.* collections.

  • You cannot return the supported operation's query plan (i.e. explain).

  • For cursors created outside of a transaction, you cannot call getMore inside the transaction.

  • For cursors created in a transaction, you cannot call getMore outside the transaction.

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()aggregateExcluding 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.
db.collection.distinct()distinctAvailable on unsharded collections.
For sharded collections, use the aggregation pipeline with the $group stage. See Distinct Operation.
db.collection.find()find
db.collection.deleteMany()
db.collection.deleteOne()
db.collection.remove()
delete
db.collection.findOneAndDelete()
db.collection.findOneAndReplace()
db.collection.findOneAndUpdate()
findAndModifyStarting 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.
In MongoDB 4.2 and earlier, if upsert: true, the operation must be run on an existing collection.
Tip

See also: 另请参阅:

DDL Operations
db.collection.insertMany()
db.collection.insertOne()
insertStarting 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: 另请参阅:

DDL Operations
db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()
updateStarting in MongoDB 4.4, if run on a non-existing collection, the collection is implicitly created.
In MongoDB 4.2 and earlier, the operation must be run on an existing collection.
Tip

See also: 另请参阅:

DDL Operations
Starting in MongoDB 4.4, if run on a non-existing collection, the collection is implicitly created.
In MongoDB 4.2 and earlier, the operation must be run on an existing collection.
Tip

See also: 另请参阅:

DDL Operations
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. For details, see Change a Document's Shard Key Value.

Count Operation

To perform a count operation within a transaction, use the $count aggregation stage or the $group (with a $sum expression) aggregation stage.

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. The 4.0 drivers have deprecated the 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.

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.

  • For sharded collections, you cannot use the db.collection.distinct() method or the distinct command.

    To find the distinct values for a sharded collection, use the aggregation pipeline with the $group stage instead. 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.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 Operations

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.

Explicit DDL Operations

CommandMethodNotes
createdb.createCollection()See also the Implicit DDL Operations.
createIndexesThe 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".

For more information on creating collections and indexes in a transaction, see Create Collections and Indexes In a Transaction.

Implicit DDL Operations

You can also implicitly create a collection through the following write operations against a non-existing collection:

Method Run against Non-Existing CollectionCommand Run against Non-Existing Collection
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
Various Bulk Operation Methods with insert or upsert:true operations

For other CRUD operations allowed in transactions, see CRUD Operations.

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.

Restricted Operations

Changed in version 4.4.

The following operations are not allowed in transactions:

Tip

See also: 另请参阅:

Pending DDL Operations and Transactions