What is the difference between createIndex()
and ensureIndex()
in Java using MongoDB? I googled this but didn't get a satisfactory answer.
I believe the original intent of the methods was that "createIndex" returns a status if the index already exists, while "ensureIndex" does not. There is no "ensureIndex" command on the server side, so the mongo shell and drivers are actually providing the "ensure" logic.
Creating an Index in MongoDB is done by using the “createIndex” method.
MongoDB provides two geospatial indexes known as 2d indexes and 2d sphere indexes using these indexes we can query geospatial data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With