Difference between createIndex() and ensureIndex() in java using mongodb Difference between createIndex() and ensureIndex() in java using mongodb mongodb mongodb

Difference between createIndex() and ensureIndex() in java using mongodb


Update 2:The original answer, as well as the first update, erroneously reference the Mongo shell documentation instead of the Java API.

In Java, DBCollection.ensureIndex() was deprecated in version 2.12 and removed in version 3.0. DBCollection.createIndex() is the one that should be used.

Update:
db.collection.ensureIndex() is deprecated since version 3.0.0.
Is now an alias for db.collection.createIndex().

Original:
createIndex() is deprecated since 1.8

It was used to create indexes on collections whereas ensureIndex() creates an index on the specified field if the index does not already exist. Moreover when we execute createIndex() twice the second execution will just fail whereas with ensureIndex() you can invoke it multiple times and it will not fail

And one more thing that they changed regarding behavior of ensureIndex(), in previous versions of mongodb(versions less then 2.6) if the index entry for an existing document exceeds the max index key length an index would be created but Mongodb would not index such documents whereas in recent version no index would be created.


In the Java API, DBCollection.ensureIndex() is deprecated, exactly the other way around compared to the "normal" MongoDB API (at the time of the response). Update: This inconsistency appears to have since been resolved, and db.collection.createIndex() now substitutes db.collection.ensureIndex() in the Mongo shell also.

As you can see in https://jira.mongodb.org/browse/JAVA-1097, in Java (which the OP asked about) ensureIndex() was deprecated in version 2.12.0 of the Java driver, and DBCollection.createIndex() is the one you need to use. DBCollection.ensureIndex() (link to version 2.12) is not available in the DBCollection Java API anymore.


The ensureIndex method found in the java driver (v2.12 and older) would cache whether or not the index exist on the collection. Since multiple clients could potentially change the indexes on a collection, the cache value may sometime be erroneous and the driver would fail to create a missing index.

For this reason, the java driver implemented a createIndex method with identical behaviour, except it won't cache the index status.

With drivers 2.12 and above, you can replace ensureIndex by createIndex and expect the same behaviour, except for the performance hit where the driver would formerly think that the index already exists and return without sending the createIndex command to the mongo server.

As to why they did not change the behaviour without renaming - that I have no idea.