Reputation: 1331
I have been trying to create a MongoDB application with Spring boot. But, before it starts it throws an exception of E11000 Dup. Key error in a collection. This error occurs at startup though I have verified all the points but, I didn't find any duplicate key in my data. My data structure looks likes
@Document( collection = "IT" )
public class ItemType {
@Id
private String id;
private IV[] iv;
}
public class IV {
private String value;
private AP[] aps;
}
@Document( collection = "AP" )
public class AP {
@Id
private String id;
@Indexed( unique = true )
private String apc;
private String dim;
private string foc;
}
Whenever I start my spring boot application it throws following exception:
E11000 duplicate key error collection: p.IT index: iv.aps.apc dup key: { : "AVI" }
My dataset is:
{
"_id" : ObjectId("5e846c5c3584fe7c7831283e"),
"iv" : [
{
"value" : "M",
"aps" : [
{
"apc" : "MOV"
},
{
"apc" : "AVI"
}
]
},
{
"value" : "N",
"aps" : [
{
"apc" : "MOV"
},
{
"apc" : "AVI"
}
]
},
{
"value" : "O",
"aps" : [
{
"apc" : "MOV"
}
]
},
{
"value" : "P",
"aps" : [
{
"apc" : "MOV"
}
]
}
]
}
I am new to MongoDB and it seems I am not making the data structure correctly. As I am willing to create reference to collection in a way that only few properties that I am using in another collection should be available there i.e. as you can see AP has more then 2 properties. But, I am using only apc which is needed by IV
Upvotes: 1
Views: 908
Reputation: 28326
You have a unique index defined in class AP
@Indexed( unique = true )
private String apc;
and then you have an array of AP object in class IV
private AP[] aps;
and an array of IV object in class IT
private IV[] iv;
The resulting index will enforce that no 2 documents can have apc
fields with the same value. An index in MongoDB is structured as a set of k
->v
pairs, where the k
is the value indexed field, and v
is the internal document identifier (not the _id). If the same value appears multiple times in a single document, it will only be added to the index once.
The unique property is enforced at the index level, so a single document can have repeats of the value since it will only result in a single entry in the index, but no other document could then use that value because it would require adding a second copy of it in the index.
To bring this back around to your data, that sample document contains 2 different values for iv.aps.apc
, MOV
, and AVI
. Since that is indexed with the unique option, no other document in that collection can have either of those values in that field.
Upvotes: 1