title: Create Indexes on MongoDB when creating collection (Java)
body: <p>I'm currently working with MongoDB and its Java Driver. On top of this, I have REST webservices which allows client to create collection and push documents in MongoDB. </p>
  
  <p>I want to automatically create indexes on specific, mandatory fields in Mongo. First, I took a look at <a href="https://docs.mongodb.com/manual/reference/method/db.collection.ensureIndex/" rel="nofollow noreferrer">ensureIndex()</a>, only to see that it was deprecated, and method <a href="https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#db.collection.createIndex" rel="nofollow noreferrer">createIndex()</a> is now recommended. </p>
  
  <p>So I could make a pretty simple method like this :</p>
  
  <pre><code>private void setCollection(String collection) {
          this.collection = mongoDB.getDataBase().getCollection(collection);
          this.collection.createIndex("key");
  }
  </code></pre>
  
  <p>According to <a href="https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#behaviors" rel="nofollow noreferrer">behaviors</a> of indexes, the method createIndex() will not rebuild an existing index.</p>
  
  <p>So my question is : is my method elegant ? Is createIndex() making a additionnal call to MongoDB to ensure that the index is already created ? Which could possibly lead to performance issue.</p>
  
  <p>Thank you for your time.</p>