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

前端 未结 2 1555
野性不改
野性不改 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).

    0 讨论(0)
  • 2020-12-17 19:53

    I found an answer on this page. I’m guessing your code looks something like this (greatly simplified)?:

    doc = {} 
    for i in xrange(2): 
        doc['i'] = i 
        collection.insert(doc) 
    

    The problem is that PyMongo injects an _id field into the document, if the _id field does not exist, before inserting it (_id is always generated client side with 10gen drivers). That means that the first time through the loop _id is added by the insert method. Since doc is defined outside the loop, each subsequent pass through the loop uses the same value for _id.

    Solution:

    1. Delete the key _id
    for i in xrange(2): 
        doc['i'] = i 
        if '_id' in doc: 
            del doc['_id'] 
        collection.insert(doc)
    
    1. Or create manually a new one:
    from bson.objectid import ObjectId 
    for i in xrange(2): 
        doc['i'] = i 
        doc['_id'] = ObjectId() 
        collection.insert(doc)
    
    0 讨论(0)
提交回复
热议问题