MongoDB allows multiple clients to read and write the same data. To ensure consistency, MongoDB uses locking and concurrency control to prevent clients from modifying the same data simultaneously.
Aggregation
Aggregation operations process multiple documents and return computed results. You can use aggregation operations to:
Group values from multiple documents together.
Perform operations on the grouped data to return a single result.
There are 2 types of data model that can be designed
Embed data model
Optimizing the performance of retrieving data
Convenient to retrieve data by single operation
No convenient to update the embed document if the same data happens on multiple collections
Reference
Convenient to keep data be consistent
Using lookup to join the collections
ACID Transaction
As multiple-document operation is not atomic, for some situation, such as bank transfer, in order to keep data consistent, ACID transaction can be used
// Example 1
const session = db.getMongo().startSession()
session.startTransaction()
const account = session.getDatabase('< add database name here>').getCollection('<add collection name here>')
//Add database operations like .updateOne() here
session.commitTransaction()
// Example 2
const session = db.getMongo().startSession()
session.startTransaction()
const account = session.getDatabase('< add database name here>').getCollection('<add collection name here>')
//Add database operations like .updateOne() here
session.abortTransaction()
In MongoDB, a write operation is on the level of a single document, even if the operation modifies multiple embedded documents within a single document.
When a single write operation (e.g. ) modifies multiple documents, the modification of each document is atomic, but the operation as a whole is not atomic.