登录
首页 >  Golang >  Go问答

MongoDB/Mongo-Go-Driver与Azure Cosmos DB的ModifiedCount和MatchedCount的工作方式存在问题

来源:stackoverflow

时间:2024-03-13 12:30:28 196浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《MongoDB/Mongo-Go-Driver与Azure Cosmos DB的ModifiedCount和MatchedCount的工作方式存在问题》,聊聊,我们一起来看看吧!

问题内容

我正在尝试使用连接到 azure cosmosdb 实例 (v3.6) 的 mongodb/mongo-go-driver (v1.2.1) 编写一个简单的 crud 测试应用程序。请考虑以下代码摘录。

client 结构中剥离 update 函数,为简洁起见,省略了该函数

func (c *client) update(ctx context.context, filter, update bson.m) error {    
    res, err := c.collection.updateone(ctx, filter, update, options.update())
    if err != nil {
        return error{errfunctional, "failed to update document", err}
    }

    if res.matchedcount != 1 {
        return error{
            code: errnotfound,
            msg:  "document not found",
        }
    }

    if res.modifiedcount != 1 {
        return error{
            code: errnotupdated,
            msg:  "document not updated",
        }
    }

    return nil
}

运行程序代码如下所示

type doc struct {
    count int
}

id, err := dbClient.Insert(context.TODO(), doc{1})
if err != nil {
    panic(fmt.Errorf("insert failed: %v", err))
}

err = dbClient.Update(context.TODO(), bson.M{"_id": id}, bson.M{"$set": bson.M{"count": 2}})
if err != nil {
    panic(fmt.Errorf("update failed: %v", err))
}

err = dbClient.Delete(context.TODO(), bson.M{"_id": id})
if err != nil {
    panic(fmt.Errorf("delete failed: %v", err))
}

正如您在代码中看到的,我正在尝试完成以下步骤:

  1. 插入一条记录 {"count": 1} (此操作正常,文档已插入)
  2. 将插入记录更新为{"count": 2}(由于未找到文档错误而失败)
  3. 删除记录(代码永远不会到达此处)

程序在第二步失败。我检查了驱动程序返回的结果,matchedcountmodifiedcount 始终为 0。但是数据库更新为正确的数据。很奇怪,对吧?现在有趣的是,如果我使用 mongodb shell(cli,使用brew 安装)执行相同的步骤,那么这些步骤完成时不会出现任何问题。

我已经尝试了过滤器和更新语句的所有变体以使其工作,但无济于事。我感觉这和golang驱动有关。我是否遗漏或做错了什么?请随时询问更多信息,我很乐意编辑问题以提供它。


解决方案


事实证明这只是连接字符串中的一个愚蠢错误。由于某种原因我使用了这种格式。

mongodb://:@.documents.azure.com:10255/?ssl=true&replicaSet=globaldb&maxIdleTimeMS=120000&retrywrites=false"

更改为这种格式,现在一切正常。

mongodb://:@.mongo.cosmos.azure:10255/?ssl=true&replicaSet=globaldb&maxIdleTimeMS=120000&retrywrites=false"

SMH。

以上就是《MongoDB/Mongo-Go-Driver与Azure Cosmos DB的ModifiedCount和MatchedCount的工作方式存在问题》的详细内容,更多关于的资料请关注golang学习网公众号!

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