Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example for transactions in mongodb with GoLang

I need an example to implement transactions in MongoDB with GoLang.

I'm using this golang driver for mongodb

https://github.com/mongodb/mongo-go-driver

There is no clear documentation for how to implement transactions.

Can anyone help me?

like image 428
Sreenath Avatar asked Jan 28 '19 09:01

Sreenath


People also ask

Can we use MongoDB for transactions?

For situations that require atomicity of reads and writes to multiple documents (in a single or multiple collections), MongoDB supports multi-document transactions. With distributed transactions, transactions can be used across multiple operations, collections, databases, documents, and shards.

Does MongoDB use Golang?

Go is one of the newest languages to get an official MongoDB driver, and the combination of Go's compiled performance and lightweight, data-friendly syntax makes Go with MongoDB a fantastic match for building data-driven applications.


2 Answers

It can be confusing. Below is a simple example.

if session, err = client.StartSession(); err != nil {
    t.Fatal(err)
}
if err = session.StartTransaction(); err != nil {
    t.Fatal(err)
}
if err = mongo.WithSession(ctx, session, func(sc mongo.SessionContext) error {
    if result, err = collection.UpdateOne(sc, bson.M{"_id": id}, update); err != nil {
        t.Fatal(err)
    }
    if result.MatchedCount != 1 || result.ModifiedCount != 1 {
        t.Fatal("replace failed, expected 1 but got", result.MatchedCount)
    }

    if err = session.CommitTransaction(sc); err != nil {
        t.Fatal(err)
    }
    return nil
}); err != nil {
    t.Fatal(err)
}
session.EndSession(ctx)

You can view full examples here.

like image 153
simagix Avatar answered Sep 17 '22 14:09

simagix


This will help you

ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
    panic(err)
}

db := client.Database("testdb")
defer db.Client().Disconnect(ctx)
col := db.Collection("testcol")

// transaction
err = db.Client().UseSession(ctx, func(sessionContext mongo.SessionContext) error {
    err := sessionContext.StartTransaction()
    if err != nil {
        return err
    }

    _, err = col.InsertOne(sessionContext, bson.M{"_id": "1", "name": "berry"})
    if err != nil {
        return err
    }

    _, err = col.InsertOne(sessionContext, bson.M{"_id": "2", "name": "gucci"})
    if err != nil {
        sessionContext.AbortTransaction(sessionContext)
        return err
    }
    if err = session.CommitTransaction(sessionContext); err != nil {
        return err
    }
    return nil
})
like image 44
berryberry Avatar answered Sep 16 '22 14:09

berryberry