I get this error while trying to insert data from a JSON file. Only one item is added to the database.
11000 E11000 duplicate key error index: awdb.mycollection.$_id_ dup
> key: { : ObjectId('53954d897aadbe032a33cd68') }
> > db.mycollection.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "awdb.mycollection"
},
{
"v" : 1,
"unique" : true,
"key" : {
"UDID" : 1
},
"name" : "UDID_1",
"ns" : "awdb.mycollection",
"sparse" : true
}
]
>
The following is the JSON input file I am using.
{"UDID":"1234","FriendlyName":"Ben Android","sn":"abc123","ManDate":"12/12/8234"}
{"UDID":"1235","FriendlyName":"Android","sn":"abc23","ManDate":"12/12/1254"}
{"UDID":"1236","FriendlyName":"Ben droid","sn":"abc12","ManDate":"12/12/1734"}
Here is the code im using to insert the JSON
while ((sCurrentLine = br.readLine()) != null) {
d=g.fromJson(sCurrentLine, Device.class);
m.create(d);
}
And here is my create function
public boolean create(Device d) {
document.put("UDID",d.UDID);
document.put("name", d.FriendlyName);
document.put("Serial", d.sn);
document.put("Manf", d.ManDate);
collection.insert(document);
return true;
}
And my Device class
public class Device {
public String UDID;
public String FriendlyName;
public String sn;
public String ManDate;
}
_idvalue is the primary key, which does not allow duplicates. It appears your JSON has the same value mentioned at least twice. You need to de-duplicate your JSON or otherwise resolve the problemdocumentbeing instantiated? Is there a new instance per loop? Or is it created outside the loop and you are just replacing the values? See the possible problems here?_idvalue that is not being overwritten. That generates on the client by default. But what I am saying is there not the relevant code posted here for anyone to tell for sure. It certainly seems that way by the error being produced. It would be clearer if we could see the code.