Can you give an example of a transaction that can span multiple collections and documents that includes reads, inserts, deletes and updates.
Hi Parvathi,
There are some examples listed on MongoDB Multi-Document Transactions manual page. You can select the Go
language tab on the examples snippet to view the examples in mongo-go-driver
.
For example, below is a transaction snippet that involves two collections and two database operations (update and insert):
updateEmployeeInfo := func(sctx mongo.SessionContext) error {
employees := client.Database("hr").Collection("employees")
events := client.Database("reporting").Collection("events")
err := sctx.StartTransaction(options.Transaction().
SetReadConcern(readconcern.Snapshot()).
SetWriteConcern(writeconcern.New(writeconcern.WMajority())),
)
if err != nil {
return err
}
_, err = employees.UpdateOne(sctx, bson.D{{"employee", 3}}, bson.D{{"$set", bson.D{{"status", "Inactive"}}}})
if err != nil {
sctx.AbortTransaction(sctx)
log.Println("caught exception during transaction, aborting.")
return err
}
_, err = events.InsertOne(sctx, bson.D{{"employee", 3}, {"status", bson.D{{"new", "Inactive"}, {"old", "Active"}}}})
if err != nil {
sctx.AbortTransaction(sctx)
log.Println("caught exception during transaction, aborting.")
return err
}
return commitWithRetry(sctx)
}
In our case, we start the transaction, and then the go routine can end up calling multiple functions that can results in read, updates, creates and delete to multiple collections in one transaction.
Worth noting that by default, a transaction must have a runtime of less than one minute. You can modify this limit using transactionLifetimeLimitSeconds
. Transactions that exceeds this limit are considered expired and will be aborted by a periodic cleanup process.
You may also find the following references useful:
Regards,
Wan.