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

Amit Chahar picture Amit Chahar · Sep 22, 2014 · Viewed 25.6k times · Source

What is the difference between createIndex() and ensureIndex() in Java using MongoDB? I googled this but didn't get a satisfactory answer.

Answer

sol4me picture sol4me · Sep 22, 2014

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.