关于MongoDB事务Callback API的疑问及实际示例需求
MongoDB事务Callback API的澄清与示例
我查阅了多篇MongoDB事务相关文档后,仍有几点疑问需要澄清:
- 有文档提到MongoDB提供两种事务API:Core API(语法类似关系型数据库)和Callback API(官方推荐用法),但后续仅介绍了Core API,完全未提及推荐的Callback API。
- MongoDB官方文档指出Callback API会自动完成启动事务、执行指定操作、提交/中止事务三个核心步骤,但关键的"执行指定操作"环节没有给出实际代码示例,导致用法模糊。
Golang版本Callback API实际示例
// WithTransactionExample is an example of using the Session.WithTransaction function. func WithTransactionExample(ctx context.Context) error { // For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g. // uri := "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl" // For a sharded cluster, connect to the mongos instances; e.g. // uri := "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/" uri := mtest.ClusterURI() clientOpts := options.Client().ApplyURI(uri) client, err := mongo.Connect(ctx, clientOpts) if err != nil { return err } defer func() { _ = client.Disconnect(ctx) }() // Prereq: Create collections. wcMajority := writeconcern.Majority() wcMajority.WTimeout = 1 * time.Second wcMajorityCollectionOpts := options.Collection().SetWriteConcern(wcMajority) fooColl := client.Database("mydb1").Collection("foo", wcMajorityCollectionOpts) barColl := client.Database("mydb1").Collection("bar", wcMajorityCollectionOpts) // Step 1: Define the callback that specifies the sequence of operations to perform inside the transaction. callback := func(sessCtx mongo.SessionContext) (interface{}, error) { // Important: You must pass sessCtx as the Context parameter to the operations for them to be executed in the // transaction. if _, err := fooColl.InsertOne(sessCtx, bson.D{{"abc", 1}}); err != nil { return nil, err } if _, err := barColl.InsertOne(sessCtx, bson.D{{"xyz", 999}}); err != nil { return nil, err } return nil, nil } // Step 2: Start a session and run the callback using WithTransaction. session, err := client.StartSession() if err != nil { return err } defer session.EndSession(ctx) result, err := session.WithTransaction(ctx, callback) if err != nil { return err } log.Printf("result: %v\n", result) return nil }
疑问解答
从上述示例可以明确:Callback API的核心业务操作确实是在回调函数内完成的。
示例关键逻辑拆解:
- 定义
callback函数,内部封装事务中需要执行的所有数据库操作(示例为向两个集合插入文档),且必须传入sessCtx作为操作的上下文参数,确保这些操作归属当前事务。 - 调用
session.WithTransaction方法执行回调,该方法会自动处理事务全流程:若回调内所有操作无异常,事务自动提交;若回调返回错误,事务自动中止并回滚。
官方文档确实应更明确地强调这一核心逻辑,避免开发者对Callback API的用法产生混淆。
内容的提问来源于stack exchange,提问作者xpt
相关产品推荐
相关产品推荐

