2
WriteConcern detected an error 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: develop.Test.$AppId_1_UserId_1_Type_1__sub_1__key_1  dup key: { ... }'. (Response was { "ok" : 1, "code" : 11000, "err" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: develop.Test.$AppId_1_UserId_1_Type_1__sub_1__key_1  dup key: {...}).

I'm getting the above error when trying to insert a new entry into my collection. The thing that is confusing me is my key is a Guid id field. The entity has AppId and UserId fields but those aren't supposed to be the key and shouldn't have to be unique.

Right before I save the Id is just all zeroes. After it is set to a unique Guid, but the save call throws the MongoDuplicateKey error. Maybe it's because I'm new to Mongo but I don't understand this any help would be appreciated.

Update

Output of get Indexes

{
    "0" : {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "develop.Test"
    },
    "1" : {
        "v" : 1,
        "unique" : true,
        "key" : {
            "AppId" : 1,
            "UserId" : 1,
            "Type" : 1,
            "_sub" : 1,
            "_key" : 1
        },
        "name" : "AppId_1_UserId_1_Type_1__sub_1__key_1",
        "ns" : "develop.Test"
    },
    "2" : {
        "v" : 1,
        "key" : {
            "Type" : 1,
            "_sub" : 1,
            "_g" : 1
        },
        "name" : "Type_1__sub_1__g_1",
        "ns" : "develop.Test"
    }
}
1
  • 1
    can you show us the output of db.collection.getIndexes() Commented Jul 28, 2015 at 18:19

1 Answer 1

2

You have a unique compound indexes on the AppId, UserId, Type, sub and key fields that is why you are getting this error.

"1" : {
        "v" : 1,
        "unique" : true,
        "key" : {
            "AppId" : 1,
            "UserId" : 1,
            "Type" : 1,
            "_sub" : 1,
            "_key" : 1
        },
        "name" : "AppId_1_UserId_1_Type_1__sub_1__key_1",
        "ns" : "develop.Test"
    },

Now how to solve the problem?

  • If you didn't create it so perhaps you co-worker or someone did. In this case you don't drop the index without talking to them.
  • You may want to drop the index using db.collection.dropIndex(index) method

    db.collection.dropIndex({ AppId: 1, UserId: 1, Type: 1, _sub: 1, _key: 1 })
    
Sign up to request clarification or add additional context in comments.

1 Comment

It turned out I just had to change _key to Key! The subject field had a [BsonElement("_sub")] tag but there wasn't one for Key so _key was always null. Thanks for pointing me in the right direction!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.