14.04.2016 | Andreas Günzel | comment icon 0 Comment

Automatically alter MongoDB indices using Morphia

In my recent project we used MongoDB as database engine and the document mapping framework Morphia as abstraction layer above. One of MongoDB’s key features is the support of indices. Using Morphia you can easily define an index using annotations as shown in listing 1:

When creating the datastore we can instruct Morphia to create all indices for us. Listing 2 provides a very basic datastore initialization that we called at application start:

This perfectly worked for us until we needed to modify existing indices for the first time. In our example the non-unique index on field user was altered to be unqiue. This unspectacular code adaption leads to a MongoCommandException and an interruption of the application start:

Ok, seems reasonable. But how to solve that? I searched the web for a solution and didn’t found any. So, I implemented a small workaround: At application start we still try to create all indices. If creation of a certain index fails, we drop that one and recreate it using the current fields and options. The final implementation is listed below:

Looks like a bunch of ugly string operations, doesn’t it? Yes, that’s right, but all we got is an error message from the MongoDB server containing the name of the index – not even the collection’s name is given to us. So, what we do is to extract the index’ name and search all collections for such an index. Names are not unique so we might drop one or more indices too much. However, this is not an issue since we create all indices for all collections afterwards.

PS: This solution works for MongoDB V2 and V3.

Happy coding,

mongodb morphia

Leave a Comment