silveur
silveur

Reputation: 167

MongoDB, how to add a unique index called "id"

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.

Upvotes: 1

Views: 798

Answers (2)

srikanth
srikanth

Reputation: 978

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

Upvotes: 0

Ali Dehghani
Ali Dehghani

Reputation: 48133

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.

Upvotes: 1

Related Questions