Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongo _id field duplicate key error

I have a collection with the _id field as a IP with type String.

I'm using mongoose, but here's the error on the console:

$ db.servers.remove()

$ db.servers.insert({"_id":"1.2.3.4"})

$ db.servers.insert({"_id":"1.2.3.5"}) <-- Throws dup key: { : null }

like image 343
EthernetCable Avatar asked Jun 14 '13 18:06

EthernetCable


People also ask

How do I fix duplicate key errors?

There are the following options for handling duplicate key errors: You can delete the file, for example if you know that there are values in the file that are not correct. You can then adjust the file and upload it again. The system will not transfer any data from files that contain duplicate instances.

How do I avoid duplicate errors in Mongodb?

If you ever faced this error all you need to do is to check your model carefully and find out that is there any unique key set true by you and if it is not necessary then simply remove the unique key from the model or otherwise set a unique value if it is necessary to be unique.

What is __ V in Mongodb?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).


2 Answers

Likely, it's because you have an index that requires a unique value for one of the fields as shown below:

> db.servers.remove()
> db.servers.ensureIndex({"name": 1}, { unique: 1})
> db.servers.insert({"_id": "1.2.3"})
> db.servers.insert({"_id": "1.2.4"})
E11000 duplicate key error index: test.servers.$name_1  dup key: { : null }

You can see your indexes using getIndexes() on the collection:

> db.servers.getIndexes()
[
    {
        "v" : 1,
        "key" : {
                "_id" : 1
        },
        "ns" : "test.servers",
        "name" : "_id_"
    },
    {
        "v" : 1,
        "key" : {
                "name" : 1
        },
        "unique" : true,
        "ns" : "test.servers",
        "name" : "name_1"
    }
]
like image 126
WiredPrairie Avatar answered Sep 22 '22 18:09

WiredPrairie


I was confused by exactly the same error today, and later figured it out. It was because I removed a indexed property from a mongoose schema, but did not drop that property from the mongodb index. The error message is infact that the new document has an indexed property whose value is null (not in the json).

like image 23
dliu Avatar answered Sep 23 '22 18:09

dliu