Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 831
Amit Chahar Avatar asked Sep 22 '14 07:09

Amit Chahar


People also ask

What is the difference between createIndex and ensureIndex in MongoDB?

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.

Which is the method used to create index in MongoDB?

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

How many indexes does MongoDB create by default for a new collection?

MongoDB provides two geospatial indexes known as 2d indexes and 2d sphere indexes using these indexes we can query geospatial data.


2 Answers

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.

like image 56
sol4me Avatar answered Sep 25 '22 00:09

sol4me


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.

like image 39
Jens Grivolla Avatar answered Sep 27 '22 00:09

Jens Grivolla