Reputation: 16610
I'm trying to ad a document (here: a dictionary) twice to a mongo-db collection. python throws an error (but it seems to work from the mongo shell)
>>> d={'a': 123, 'b': 'abcde'}
>>> collection.insert(d)
>>> collection.insert(d)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
[...]
DuplicateKeyError: E11000 duplicate key error index: test_database.test_collection.$_id_ dup key: { : ObjectId('52edc7cda9658c12603db9af') }
why is that an error? i didn't specify any ID.
Upvotes: 1
Views: 218
Reputation: 1121
The problem is that on the first insert, the shell would automatically create an objectid for you before inserting it into the collection. then when you try to insert the exact same document (with the Object Id) you would have a duplicate key error since the collection already has a doc with the same ID.
If you really want to insert the same doc twice, try deleting the ObjectId from the doc, and then insert.
Try,
d={'a': 123, 'b': 'abcde'}
db.collection.insert(d);
d={'a': 123, 'b': 'abcde'}
db.collection.insert(d);
Upvotes: 3