Getting “err” : "E11000 duplicate key error when inserting into mongo using the Java driver

前端 未结 2 1557
野性不改
野性不改 2020-12-17 18:57

Exception in thread \"main\" com.mongodb.MongoException$DuplicateKey: { \"serverUsed\" : \"localhost/127.0.0.1:27017\" , \"err\" : \"E11000 duplicate key

2条回答
  •  借酒劲吻你
    2020-12-17 19:43

    Try calling myIdMapCollection.save(myObj); instead of myIdMapCollection.insert(myObj);

    The save method, unlike insert does upsert, meaning if a document contains _id, it replaces that document.

    My guess is that you had fetched the DBObject using a cursor | query, had manipulated it, and you want to persist the changes. In that case, save is the right way to do it.

    So, when calling insert the DBObject is already associated with _id, calling insert thus fails, because you already have a document with that _id in the collection, which should be unique (duplicate index error).

提交回复
热议问题