Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index already exists with different options error while using createIndex() in latest MongoDB java driver

So I am upgrading the MongoDB java driver to 2.12.4 where the ensureIndex() method has been deprecated. I am instead using the createIndex() method which from the docs seems like to funciton similarly to ensureIndex(). However, when I use this method in production, I get the following error -

{ "serverUsed" : "X.X.X.X" , "ok" : 0.0 , "errmsg" : "Index with name: <index_name> already exists with different options" , "code" : 85}

Why does this happen? Could anyone help me out with this?

Thanks

like image 342
gravetii Avatar asked Dec 04 '14 07:12

gravetii


People also ask

What is createIndex in MongoDB?

The indexes are ordered by the value of the field specified in the index. So, MongoDB provides a createIndex() method to create one or more indexes on collections. Using this method we can create different types of indexes like text index, 2dsphere index, 2d index, etc.

Which of the following is the correct method to create indexes on a collection in MongoDB?

Creating an Index in MongoDB is done by using the “createIndex” method.

When the index does not exist which method will be used for creating an index on the specified field?

Create an Index : Along with the default index, we can create indexes on our own using the createIndex() method. This method creates one or more indexes on the specified collections.

How do I set unique values in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .


2 Answers

Try removing your current indexes before you create the new ones.

If you're worried about production downtime etc for these indexes, you could:

  1. Add a second index just like the one you have on production now with a different name.
  2. delete the existing one
  3. restart the server so that the index in your Java code is created as expected
  4. delete your duplicate index.
like image 106
Will Shaver Avatar answered Sep 22 '22 14:09

Will Shaver


Will Shaver's answer is very good, however doesn't actually address the issue the gravetii is highlighting.

createIndex will fail with this error if you are trying to create an index on the same fields, with the same order, but with different options. This is because the indexes options may cause the index have very different properties. This is obvious when you consider an index with the unique flag.

If you call createIndex with the same fields, the same order, and the same options, it will behave as you expect; making no change to the collection's indexes, and it will not throw an exception.

like image 33
idbentley Avatar answered Sep 24 '22 14:09

idbentley