【问题标题】:UpdateOne failed with E11000 duplicate key errorUpdateOne 因 E11000 重复密钥错误而失败
【发布时间】:2019-06-28 16:14:04
【问题描述】:

我正在尝试从 go 更新 MongoDB 的文档。

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
c, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
col := c.Database("epgrec").Collection("rec")
filter := bson.M{"_id": r.Mid}
update := bson.M{
    "$set": bson.M{
        "rid":        r.Rid,
        "channel":    r.Channel,
        "sid":        r.Sid,
        "pid":        r.Pid,
        "start":      r.Start,
        "duration":   r.Duration,
        "title":      r.Title,
        "status":     r.Status,
        "cmdarray":   r.CmdArray,
        "workingdir": r.WorkingDir,
    },
}
res, err := col.UpdateOne(ctx, filter, update)

下面有错误。

multiple write errors: [{write errors: [{E11000 duplicate key error collection: epgrec.rec index: _id_ dup key: { : ObjectId('5d163936ead22a4f85f1e607') }}]}, {<nil>}]
exit status 1

使用 MongoDB 驱动程序 v1.0.3(来自 go.mongodb.org/mongo-driver/mongo)

如何避免此错误?请帮忙。

【问题讨论】:

  • 您好,mkiuchi,欢迎来到堆栈溢出。请更新您的问题,使其成为一个完整且可验证的示例。我应该能够运行您的代码并重现结果。在创建完整示例的过程中,请确保它尽可能简单——这可能很难,但在此过程中您会经常找到答案。请参阅此处stackoverflow.com/help/minimal-reproducible-example 了解更多信息。
  • 你能运行db.rec.getIndexes()并分享输出吗?

标签: mongodb go mongo-go


【解决方案1】:

似乎有记录,其中您的对象映射已经存在于 id,我建议您阅读有关 unique indexessparse indexes 的相关文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-16
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2014-07-02
    • 2016-08-03
    • 2020-05-21
    相关资源
    最近更新 更多