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"}})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥20 powerbulider 导入excel文件,显示不完整
    • ¥20 #关于multisim绘图遇到的问题
    • ¥15 用keil调试程序保证结果进行led相关闪烁
    • ¥15 paddle训练自己的数据loss降不下去
    • ¥20 用matlab的pdetool解决以下三个问题
    • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?
    • ¥15 嵌入式Linux固件,能直接告诉我crc32校验的区域在哪不,内核的校验我已经找到了,uboot没有
    • ¥20 h3c静态路要求有详细过程
    • ¥15 调制识别中输入为时频图,星座图,眼图等
    • ¥15 数据结构C++的循环、随机数问题