3

I am using mongojs and Node.js to insert a document in mongodb. It is a REST API and there is only one instance of mongojs (with native drive). Everytime, there is an api call, SAME mongojs object is used to perform mongodb operations. Now, I get the following error when trying to insert a document.

{
name: "MongoError"
err: "E11000 duplicate key error index: testdb.userComment.$_id_ dup key: { :    ObjectId('51727190bb4ab52a80024c09') }"
code: 11000
n: 0
connectionId: 225
ok: 1
}

The document is always unique I tried db.userComment.getIndexs() and it shows the index is on _id . Can anyone help me how I can fix this problem ?

codejammer
  • 469
  • 1
  • 7
  • 18
  • `_id` must be unique in MongoDB. If you have a new document, it's easiest if you just don't set the `_id` field and one will be automatically assigned by either the driver or the database. Either way, it will be unique. – WiredPrairie Apr 21 '13 at 18:07

2 Answers2

1

I am not sure whether its a right fix, but everytime a document is inserted, I am explicitly creating a new ObjectID instead leaving the fate to mongodb driver. I used the following piece of code

commentData._id = require('mongodb').BSONPure.ObjectID();

codejammer
  • 469
  • 1
  • 7
  • 18
-1

This question seems to be a duplicate of this one : Getting "err" : "E11000 duplicate key error when inserting into mongo using the Java driver

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)
Community
  • 1
  • 1
Florian
  • 874
  • 1
  • 8
  • 17