Table of Contents
What is ACID?
Multi-document transactions: support scope
How to use transactions (example)
Transaction usage restrictions and precautions
Single document atomicity: the first choice for daily development
Summarize
Home Database MongoDB ACID Transactions in MongoDB

ACID Transactions in MongoDB

Jul 30, 2025 am 12:02 AM
mongodb ACID事务

Yes, MongoDB supports ACID transactions. 1. It supports single-document ACID operations from version 4.0, and multi-document transactions from 4.2, including replica sets and shard clusters. 2. Multi-document transactions need to be started through a session. All operations must be passed in session. Try-catch handles commits or rollbacks, and finally call endSession to release resources. 3. The transaction has a 60-second default timeout limit, and the performance overhead is high. Especially cross-sanded transactions require mongos coordination, which should avoid long-term or high-frequency use; 4. Eval, mapReduce and other commands are disabled in the transaction, and read and write attention and read preferences must be set at the transaction level; 5. It is recommended to use single-document atomic operations first, and use transactions through embedded data models to reduce transaction requirements to improve performance and scalability; 6. It is suitable for strong consistency scenarios such as transfer and inventory deduction, but the transaction time should be shortened as much as possible to avoid blockage. MongoDB's ACID capability can meet most scenarios, and the key is to choose the usage method according to the business reasonably.

ACID Transactions in MongoDB

MongoDB supports ACID transactions, but its implementation is different from traditional relational databases, especially in distributed environments with usage limitations and best practices. The following is a few key points to illustrate ACID transactions in MongoDB.

ACID Transactions in MongoDB

What is ACID?

ACID is the four key properties of database transactions:

  • A tomicity: All operations in a transaction are either successful or fail.
  • C onsistency: Before and after the transaction is executed, the database is in a consistent state.
  • I solation: Concurrent transactions do not interfere with each other.
  • D urability: Once a transaction is committed, the result is permanent.

In MongoDB, starting from version 4.0, single-document operations are ACID by default . Starting in version 4.2, MongoDB supports multi-document ACID transactions , including across multiple collections, databases, and even sharded clusters (gradually supported from 4.2).

ACID Transactions in MongoDB

Multi-document transactions: support scope

MongoDB's multi-document transaction supports the following scenarios:

  • Replica Set : Supported from 4.0.
  • Sharded Cluster : Supported since 4.2, but with more limitations and performance considerations.

Note: Cross-shash transactions require coordinator (mongos) to participate, which has greater performance overhead. It is recommended to avoid high-frequency use as much as possible.

ACID Transactions in MongoDB

How to use transactions (example)

Here is an example of a multi-document transaction using Node.js driver:

 const session = client.startSession();
session.startTransaction();

try {
  const db = client.db('bank');

  // Deduct the balance of the three await db.collection('accounts').updateOne(
    { name: 'zhangsan', balance: { $gte: 100 } },
    { $inc: { balance: -100 } },
    { session }
  );

  // Increase Li Si balance await db.collection('accounts').updateOne(
    { name: 'lisi' },
    { $inc: { balance: 100 } },
    { session }
  );

  await session.commitTransaction();
  console.log('Transfer successfully');
} catch (error) {
  await session.abortTransaction();
  console.error('Transaction failed, rolled back', error);
} finally {
  await session.endSession();
}

Key points:

  • session must be used to start the transaction.
  • All operations must be passed in session parameters.
  • Use try-catch to handle exceptions and roll back.
  • Finally, endSession() is called to release the resource.

Transaction usage restrictions and precautions

  • High performance overhead : transactions will be locked, and long-running transactions may cause blockage.
  • Timeout limit : By default, transactions must be completed within 60 seconds (can be adjusted via transactionLifetimeLimitSeconds , but it is not recommended to be too long).
  • Some commands cannot be used across multiple shard transactions : such as eval , mapReduce , etc.
  • ReadConcern, writeConcern, and readPreference need to be set at the transaction level and cannot be specified separately in the operation.

suggestion:

  • Shorten the transaction execution time as much as possible.
  • Avoid performing network requests or time-consuming calculations in transactions.
  • Priority is given to single document atomic operations, and no transactions can be used.

Single document atomicity: the first choice for daily development

MongoDB's single document update naturally supports atomicity. For example:

 db.accounts.updateOne(
  { name: "zhangsan", balance: { $gte: 50 } },
  { $inc: { balance: -50 }, $push: { history: "paid 50" } }
)

This operation is atomic: either all succeed or fail, and there will be no situation where only money is deducted and history is not recorded.

Design recommendation : Putting relevant data in one document through embedded documents or arrays can avoid multi-document transactions, improve performance and scalability.


Summarize

  • MongoDB supports ACID transactions, including multi-document transactions (replica sets and shard clusters).
  • Transactions are suitable for short-term operations with strong consistency requirements , such as financial transfers, inventory deductions, etc.
  • In daily development, it is preferred to use data modeling with reasonable operation of single-document atoms to avoid transactions.
  • Be cautious when using transactions in sharded clusters, pay attention to performance and timeout limits.

Basically, MongoDB's ACID capabilities are enough to cope with most scenarios. The key is to choose the usage method according to business needs.

The above is the detailed content of ACID Transactions in MongoDB. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Beginner's Guide to RimWorld: Odyssey
1 months ago By Jack chen
PHP Variable Scope Explained
4 weeks ago By 百草
Tips for Writing PHP Comments
3 weeks ago By 百草
Commenting Out Code in PHP
3 weeks ago By 百草

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1509
276
MongoDB vs. Oracle: Exploring NoSQL and Relational Approaches MongoDB vs. Oracle: Exploring NoSQL and Relational Approaches May 07, 2025 am 12:02 AM

In different application scenarios, choosing MongoDB or Oracle depends on specific needs: 1) If you need to process a large amount of unstructured data and do not have high requirements for data consistency, choose MongoDB; 2) If you need strict data consistency and complex queries, choose Oracle.

Various ways to update documents in MongoDB collections Various ways to update documents in MongoDB collections Jun 04, 2025 pm 10:30 PM

The methods for updating documents in MongoDB include: 1. Use updateOne and updateMany methods to perform basic updates; 2. Use operators such as $set, $inc, and $push to perform advanced updates. With these methods and operators, you can efficiently manage and update data in MongoDB.

MongoDB's Purpose: Flexible Data Storage and Management MongoDB's Purpose: Flexible Data Storage and Management May 09, 2025 am 12:20 AM

MongoDB's flexibility is reflected in: 1) able to store data in any structure, 2) use BSON format, and 3) support complex query and aggregation operations. This flexibility makes it perform well when dealing with variable data structures and is a powerful tool for modern application development.

How to view all databases in MongoDB How to view all databases in MongoDB Jun 04, 2025 pm 10:42 PM

The way to view all databases in MongoDB is to enter the command "showdbs". 1. This command only displays non-empty databases. 2. You can switch the database through the "use" command and insert data to make it display. 3. Pay attention to internal databases such as "local" and "config". 4. When using the driver, you need to use the "listDatabases()" method to obtain detailed information. 5. The "db.stats()" command can view detailed database statistics.

MongoDB vs. Oracle: Document Databases vs. Relational Databases MongoDB vs. Oracle: Document Databases vs. Relational Databases May 05, 2025 am 12:04 AM

Introduction In the modern world of data management, choosing the right database system is crucial for any project. We often face a choice: should we choose a document-based database like MongoDB, or a relational database like Oracle? Today I will take you into the depth of the differences between MongoDB and Oracle, help you understand their pros and cons, and share my experience using them in real projects. This article will take you to start with basic knowledge and gradually deepen the core features, usage scenarios and performance performance of these two types of databases. Whether you are a new data manager or an experienced database administrator, after reading this article, you will be on how to choose and use MongoDB or Ora in your project

Commands and parameter settings for creating collections in MongoDB Commands and parameter settings for creating collections in MongoDB May 15, 2025 pm 11:12 PM

The command to create a collection in MongoDB is db.createCollection(name, options). The specific steps include: 1. Use the basic command db.createCollection("myCollection") to create a collection; 2. Set options parameters, such as capped, size, max, storageEngine, validator, validationLevel and validationAction, such as db.createCollection("myCappedCollection

Operation commands to sort documents in MongoDB collection Operation commands to sort documents in MongoDB collection Jun 04, 2025 pm 10:27 PM

In MongoDB, you can use the sort() method to sort documents in a collection. 1. Basic usage: Sort by specifying fields and sorting order (1 is ascending and -1 is descending), such as db.products.find().sort({price:1}). 2. Advanced usage: It can be sorted according to multiple fields, such as db.products.find().sort({category:1,price:-1}). 3. Performance optimization: Using indexing, avoiding oversorting and paging sorting can improve efficiency, such as db.products.createIndex({price:1}) and db.products.f

What is GridFS, and when should it be used for storing large binary files in MongoDB? What is GridFS, and when should it be used for storing large binary files in MongoDB? Jun 06, 2025 am 10:50 AM

GridFS is a tool in MongoDB for storing and retrieving files with a size limit of more than 16MBBSON. 1. It divides the file into 255KB blocks, stores them in the fs.chunks collection, and saves the metadata in the fs.files collection. 2. Suitable situations include: more than 16MB of files, the need to manage files and metadata uniformly, access to specific parts of the file, and using MongoDB without introducing external storage systems. 3. GridFS is automatically stored in chunks when uploading, reorganizes files in order when reading, and supports custom metadata and multi-version storage. 4. Alternative solutions include: storing the file path in MongoDB and actually storing it in the file system,

See all articles