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 .
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.
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<Document> docs = new ArrayList<>();
docs.add(document);
try{
collection.insertMany(docs, unordered.ordered(false));
}catch(Exception e){
//System.out.println(e.getMessage());
}