0

I'm trying to update document of MongoDB from go.

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)

I've got error below.

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

using MongoDB Driver v1.0.3 (from go.mongodb.org/mongo-driver/mongo)

How do I avoid this error? Please help.

mkiuchi
  • 3
  • 3
  • 1
    Hello, mkiuchi, and welcome to stack overflow. Please update your question to be a complete and verifiable example. I should be able to run your code and reproduce the result. In the process of creating a complete example, please ensure that it is as simple as can be -- this can be hard, but in the process you will frequently find the answer. Please see here https://stackoverflow.com/help/minimal-reproducible-example for more information. – Keozon Jun 28 '19 at 17:55
  • can you run `db.rec.getIndexes()` and share the output? – RickyA Jun 28 '19 at 18:12
  • Potentially related: https://stackoverflow.com/questions/29305405/mongodb-impossible-e11000-duplicate-key-error-dup-key-when-upserting – joe Jul 05 '20 at 17:22

1 Answers1

1

It seems as if there are records where your object mapping already exists for the id, I would encourage you to read the relevant documentation about unique indexes and sparse indexes