mongodb - 使用 mongodb/mongo-go-driver 和 Azure CosmosDB 的 ModifiedCount 和 MatchedCount 不正确

标签 mongodb azure go azure-cosmosdb azure-cosmosdb-mongoapi

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

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://<username>:<password>@<app>.documents.azure.com:10255/?ssl=true&replicaSet=globaldb&maxIdleTimeMS=120000&retrywrites=false"

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

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

SMH。

关于mongodb - 使用 mongodb/mongo-go-driver 和 Azure CosmosDB 的 ModifiedCount 和 MatchedCount 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59742023/

相关文章:

python - 带有 Microsoft API 365 的 Django - 服务发现错误

Azure DevOps 构建管道 : CI triggers not working on PR merge to master when PR set to none

go - 如何确定对象是否为复合(类型)

java - 从 spring mongo 查询获取 "_id"而不是整个对象/对象列表

node.js - MongoDB:findOne 返回 null 但文档存在于集合中

node.js - 使用 NodeJs Mongo 和 Express 保留更新时的哈希密码

node.js - Mongo $ min和$ max,或并行排序

azure - 使用连接器更新 Azure ARM 模板

html - Hugo 不显示子目录 [File.Dir] 中的页面

go - 是否可以返回指向 go 共享库中结构的指针?