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 check the version of MongoDB?
- How to create a many to many relation in MongoDB?
- How to perform a health check for MongoDB?
- How to use watch in MongoDB?
- How to use unwind in MongoDB?
- How to update an array element in MongoDB?
- How to use MongoDB queue?
- How to do text search in MongoDB?
- How to set MongoDB oplog?
- How to insert many docs in MongoDB?
See more codes...