1

I'm trying to add an index called "id" in my collection but it returns:

E11000 duplicate key error index: collec.items.$id_1 dup key: { : -27 }

Is it before of a conflict between _id and id? I really need the id field to be unique to avoid duplicates.

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
silveur
  • 157
  • 1
  • 9

2 Answers2

1

Is it before of a conflict between _id and id?

No, it's not a conflict. You're adding a unique index on a field that currently contains duplicate values (one of these duplicates is -27), so MongoDB complains with:

E11000 duplicate key error index: collec.items.$id_1 dup key: { : -27 }

First remove the duplicate values and then try to add the index.

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
0

Are you trying to update the existing _id with id ? Then mongo doesn't allow to do so. Instead create a document. _id is unique identifier for mongo documents.

Creating the document with the unique id as you require,

>use db.docname.insert( { id:12345, name:"name" })
WriteResult({ "nInserted" : 1 })
>db.idreplace.find().pretty()
{
        "_id" : ObjectId("57592f1f2aa2b6057f3286ce"),
        "id" : 12345,
        "name" : "name"
}

OR

to add id to the existing document follow: Add new field to a collection in MongoDB

Community
  • 1
  • 1
srikanth
  • 958
  • 16
  • 37