dr2898 2019-04-17 10:19
浏览 144
已采纳

使用FindAndModify在官方的Mongo Go驱动程序中运行查询

In the community driven Mongo driver for Go, i.e. Mgo, we can use the Apply API call to run MongoDB queries involving $set or $inc. An example of this use-case in Mgo is as follows:

change := mgo.Change{
    Update:    bson.M{"$set": bson.M{"phone": "+55 53 8402 8510"}},
    ReturnNew: true,
}
_, err = MongoSession.DB("test").C("people").Find(bson.M{"_id": a}).Apply(change, &result)

Quoting the official documentation for this API call:

Apply runs the findAndModify MongoDB command, which allows updating, upserting or removing a document matching a query and atomically returning either the old version (the default) or the new version of the document (when ReturnNew is true).

I am currently working on porting a project from Mgo to the official Mongo Go driver. However, I am unable to find any method that runs the findAndModify command to achieve a similar use-case. For replacing the Apply API with a relevant method from the official driver, what would be the recommended approach?

I have considered examining the query under 'Update' in the existing code, and manually using the Find/Update/Replace methods provided in the official driver. But, would there be any better way to do the same?

  • 写回答

1条回答 默认 最新

  • douxiong2001 2019-04-17 10:39
    关注

    I was able to solve this using the FindOneAndUpdate API.

    It internally uses FindAndModify, even though it is not explicitly mentioned in the documentations. Code I used to emulate this feature of Mgo in Go's Mongo Driver is as follows:

    MongoSession, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
    if err != nil {
        panic(err)
    }
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    err = MongoSession.Connect(ctx)
    collection := MongoSession.Database("test").Collection("people")
    a, err := primitive.ObjectIDFromHex("XXXXXXXXXX") //hiding hex value
    b := collection.FindOneAndUpdate(ctx, bson.M{"_id": a}, bson.M{"$set": bson.M{"phone": "Replacing using the query"}})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置