Transactions that span multiple collections and documents

973 views
Skip to first unread message

parvathi nair

unread,
Jun 5, 2019, 12:47:28 PM6/5/19
to mongodb-go-driver
Can you give an example of a transaction that can span multiple collections and documents that includes reads, inserts, deletes and updates.
It also does not have to be from the same function.

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.

Is there a best practice guideline for this? Can you include an example for this case?

Thanks,
Parvathi.

Wan Bachtiar

unread,
Jun 7, 2019, 12:15:25 AM6/7/19
to mongodb-go-driver

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.

Muthu

unread,
Sep 11, 2019, 8:32:57 AM9/11/19
to mongodb-go-driver
Hi Wan

The example looks good But am not able to find a Go Tab in the link you've listed here Mongodb link transactions

Can you let me know how a commitWithRetry function work?

parvathi nair

unread,
Nov 22, 2019, 2:04:24 PM11/22/19
to mongodb-go-driver
Hi Wan,

I do not find a Tab for Golang for BulkWrite across collections in Mongodb link transactions.
I am also not able to locate any good examples in https://github.com/mongodb/mongo-go-driver/tree/master/mongo
Can u please point us to some example of bulk insert/remove/update across collections?

Thanks,
Parvathi.

Muthu

unread,
Nov 22, 2019, 3:39:13 PM11/22/19
to mongodb-go-driver

Divjot Arora

unread,
Nov 22, 2019, 3:46:02 PM11/22/19
to mongodb-go-driver
Hi Parvathi,

We recently added better documentation for sessions and transactions. You can see documentation for the overarching Session type at http://localhost:8000/pkg/go.mongodb.org/mongo-driver/mongo/#Session. To manually execute a transaction, you can use the mongo.WithSession function (http://localhost:8000/pkg/go.mongodb.org/mongo-driver/mongo/#WithSession). This can be done using the Session.StartTransaction and Session.CommitTransaction/Session.AbortTransaction functions. For a more automated way of doing this, see the example connected to http://localhost:8000/pkg/go.mongodb.org/mongo-driver/mongo/#Client.StartSession for an example using the WithTransaction API. This API will execute the callback in a transaction and retry the callback correctly on different types of errors for up to 120 seconds.
Reply all
Reply to author
Forward
0 new messages