使用GoLang在mongodb中进行交易的示例 [英] Example for transactions in mongodb with GoLang
本文介绍了使用GoLang在mongodb中进行交易的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个示例来使用GoLang在MongoDB中实现事务.
I need an example to implement transactions in MongoDB with GoLang.
我正在为mongodb使用此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.
有人可以帮助我吗?
推荐答案
这可能会造成混淆.下面是一个简单的示例.
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.
这篇关于使用GoLang在mongodb中进行交易的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文