登录
首页 >  Golang >  Go问答

阅读 Golang 中 *mongo.UpdateResult 类型的数据(包括 UpdateOne 和 $addToSet 操作)的方法

来源:stackoverflow

时间:2024-02-13 11:36:22 104浏览 收藏

一分耕耘,一分收获!既然都打开这篇《阅读 Golang 中 *mongo.UpdateResult 类型的数据(包括 UpdateOne 和 $addToSet 操作)的方法》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我正在利用 go mongodb 驱动程序查找并更新 mongodb 中的一条记录,它按预期工作。我正在努力处理 collection.updateone (类型为 *mongo.updateresult)的返回值。这是函数

func AddPaidByYYYYmm(id string, YYYYmm string) (int, error) {
    ctx := context.Background()
    _id, err := primitive.ObjectIDFromHex(id)
    if err != nil {
        log.Fatal(err)
    }
    if !CheckYearMonthFormat(YYYYmm) {
        return 0, errors.New("ill-formed date format; must be YYYY-mm")
    }
    result, err := collection.UpdateOne(ctx, bson.M{"_id": _id}, bson.M{"$addToSet": bson.M{"paid": YYYYmm}})
    fmt.Println(result)
    if err != nil {
        log.Fatal(err)
    }
    if result.MatchedCount == 0 {
        return 0, errors.New("no document matched id")
    }
    return 1, nil
}

以下是我看到的三个场景及其各自的返回值(所有这些都是 *mongo.updateresult 类型):

  1. 未找到记录,字符串未添加到 mongodb:&{0 0 0 }
  2. 找到记录,字符串已添加到数据库中的数组中:&{1 1 0 }
  3. 找到记录,字符串已在数据库中但未添加:&{1 0 0 }

问题是,我不知道如何读取这些数据。任何有关如何实现这一目标的指导都会有所帮助。如果我有任何不清楚的地方或者有人有任何疑问,请告诉我。


正确答案


请参阅 mongo.updateresult 的文档

type updateresult struct {
    matchedcount  int64       // the number of documents matched by the filter.
    modifiedcount int64       // the number of documents modified by the operation.
    upsertedcount int64       // the number of documents upserted by the operation.
    upsertedid    interface{} // the _id field of the upserted document, or nil if no upsert was done.
}
  1. 未找到记录,字符串未添加到 mongodb:&{0 0 0 }

    &mongo.updateresult{matchedcount:0, modifiedcount:0, upsertedcount:0, upsertedid:接口 {}(nil)}

  2. 找到记录,字符串已添加到数据库中的数组中:&{1 1 0 }

    &mongo.updateresult{matchedcount:1, modifiedcount:1, upsertedcount:0, upsertedid:接口 {}(nil)}

  3. 找到记录,字符串已在数据库中但未添加:&{1 0 0 }

    &mongo.updateresult{matchedcount:1, modifiedcount:0, upsertedcount:0, upsertedid:接口 {}(nil)}

输出结果用 fmt.printf("%#v\n", result) 打印,参见 https ://pkg.go.dev/fmt

%#v a Go-syntax representation of the value

今天关于《阅读 Golang 中 *mongo.UpdateResult 类型的数据(包括 UpdateOne 和 $addToSet 操作)的方法》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>