mongodbHow to use transactions in MongoDB?
MongoDB transactions provide atomicity, consistency, isolation, and durability (ACID) guarantees for operations within a single document. Transactions allow developers to execute multiple operations in a single atomic operation, either all of the operations will succeed or none of them will.
Example code
// Start a session
const session = db.startSession();
// Start a transaction
session.startTransaction();
// Insert a document
db.collection.insertOne({
_id: 1,
name: 'John Doe'
}, { session });
// Update a document
db.collection.updateOne({
_id: 1
}, {
$set: {
name: 'Jane Doe'
}
}, { session });
// Commit the transaction
session.commitTransaction();
// End the session
session.endSession();
Output example
WriteResult({ "nInserted" : 1 })
Code explanation
-
const session = db.startSession();
- This line starts a session. -
session.startTransaction();
- This line starts a transaction. -
db.collection.insertOne({ _id: 1, name: 'John Doe' }, { session });
- This line inserts a document with the given data. -
db.collection.updateOne({ _id: 1 }, { $set: { name: 'Jane Doe' } }, { session });
- This line updates the document with the given data. -
session.commitTransaction();
- This line commits the transaction. -
session.endSession();
- This line ends the session.
Helpful links
More of Mongodb
- How to use watch in MongoDB?
- How to empty an array in MongoDB?
- How to check the version of MongoDB?
- How to use triggers in MongoDB?
- How to use unwind in MongoDB?
- How to list MongoDB users?
- How to sort MongoDB query results?
- How to convert MongoDB ObjectId to string?
- How to rename a field in MongoDB?
- How to perform a health check for MongoDB?
See more codes...