我正在尝试使用连接到 Azure CosmosDB 实例 (v3.6)的 mongodb/mongo-go-driver (v1.2.1) 编写一个简单的 CRUD 测试应用程序。考虑以下代码摘录。Update从结构中剥离函数,Client为简洁起见省略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}Runner 代码如下所示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))}正如您在代码中看到的,我正在尝试完成以下步骤:插入记录{"count": 1}(这可以正常工作并插入文档)将插入记录更新为{"count": 2}(Fails due to no document found 错误)删除记录(代码永远不会到达这里)程序在第二步失败。我检查了驱动程序返回的结果,两者MatchedCount都ModifiedCount为0。但是数据库已更新为正确的数据。很奇怪,对吧?现在有趣的是,如果我使用 MongoDB shell(CLI,使用 brew 安装)执行相同的步骤,那么这些步骤将毫无问题地完成。我已经尝试了过滤器和更新语句的所有变体以使其工作,但无济于事。我有一种感觉,它与 Golang 驱动程序有关。我有什么遗漏或做错了吗?请随时询问更多信息,我很乐意编辑问题以提供它。
1 回答

倚天杖
TA贡献1828条经验 获得超3个赞
原来这只是连接字符串中的一个愚蠢的错误。出于某种原因,我使用了这种格式。
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。
- 1 回答
- 0 关注
- 140 浏览
添加回答
举报
0/150
提交
取消