title: MongoDB Java Driver: Insert document if it does not exist else do nothing
body: <p>I'm trying to write a Java function that inserts a list of words into a collection. I want one document for each word with the unique field "word".
  The list of words I want to insert contains many duplicates so I want my function to only insert the document if there isn't already a document with the same "word"-value inside the collection. If there's already a document with the same "word"-value the function should not change or replace this document but go on inserting the next word from my list .</p>
  
  <p>I created an index on the field "word" to avoid duplicate documents and catch the duplicate key Exception but I'm not sure if this is the right way to handle this issue.</p>
  
  <pre><code>    IndexOptions uniqueWord = new IndexOptions().unique(true);
      collection.createIndex(Indexes.ascending("word"), uniqueWord);
  
  
          try {
              File file = new File("src/words.txt");
              Scanner scanner = new Scanner(file);
  
  
              while (scanner.hasNextLine()) {
                    String word= scanner.next();
  
                      Document document = new Document();
                      document.put("word", word);
  
                      InsertManyOptions unordered= new InsertManyOptions();
                      ArrayList&lt;Document&gt; docs = new ArrayList&lt;&gt;();
                      docs.add(document);
  
                      try{
                      collection.insertMany(docs, unordered.ordered(false));
                      }catch(Exception e){
                          //System.out.println(e.getMessage());
                      }
  </code></pre>