DuplicateKeyException

Hello Team,

I am getting below error after I upgraded Mongo form 4.4.16 to 5.0.23 ( I am using mongodb along with opensearch and graylog)

com.mongodb.DuplicateKeyException: Write failed with error code 11000 and error message ‘Index build failed: 86186019-10e4-462d-ac4f-24895467fad8: Collection graylog.users ( d3f3f594-8493-4349-9a3a-c48709ac57a0 ) :: caused by :: E11000 duplicate key error collection: graylog.users index: unique_username dup key: { username: “haryko” }’
at com.mongodb.internal.operation.CreateIndexesOperation.checkForDuplicateKeyError(CreateIndexesOperation.java:266) ~[graylog.jar:?]
at com.mongodb.internal.operation.CreateIndexesOperation.access$200(CreateIndexesOperation.java:70) ~[graylog.jar:?]

since I was having backup and when checked for help over the internet I found that we need to do below steps

use mydb
db.users.drop()

Do we have any alternative rather dropping db or its absolutely file to drop since it will re genrate that but I am not sure.

I need guidance why this issue has occurred and what the best way to resolve this, also db.users.drop() is safe command if this issue occurs again

Please guide,

Regards,
Sam

Hi @sameer_khamkar and welcome to the community forum!!

Firstly,

the above error occurs when you try to insert a same value for a primary key like _id which is already present inside the collection.
In the above error, it seems, you are trying to insert a value for username: “haryko” which is already present inside the collection and a unique key index is. created on the userName field.

If your application requires, username to be unique, you will have to update the document value.

Secondly,

Could you help me understand what are trying to achieve due to which you are seeing error ?

The drop() command will drop the collection selected. It is safe to delete given that you do not need the collection any longer.
It would be helpful for us to understand better if you share the steps along with the motive of what you are trying to achieve.

Finally, I see that the post is being tagged with Java, are you seeing this error while performing the steps in Java application or this happens while using mongo shell too?
In either case, could you also share the MongoDB, Java and the driver version that you are using?

Regards
Aasawari

1 Like

Hello Asawari,

Thank you for your time and detailed information, I am using Graylog along with Mongo and Opensearch.
I want to remove duplicate keys from graylog.users index: unique_username can you provide me exact command to locate these data, since I am not able to get these details.
and by referring few post over the internet I am removing collection itself to resolve this issue.

Please guide me here