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 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上