모음에 단어 목록을 삽입하는 Java 함수를 작성하려고합니다. 고유 한 필드 "단어"가있는 각 단어에 대해 하나의 문서를 원합니다. 삽입하려는 단어 목록에 여러 개의 중복이 포함되어 있으므로 컬렉션에 동일한 "단어"값이있는 문서가없는 경우에만 문서에 삽입하는 기능이 필요합니다. 동일한 "단어"값을 가진 문서가 이미있는 경우이 함수는이 문서를 바꾸거나 바꾸지 말고 목록에서 다음 단어를 삽입해야합니다.MongoDB Java Driver : 문서가없는 경우 문서를 삽입하십시오. else do nothing
중복 된 문서를 피하고 중복 키 예외를 잡기 위해 "단어"필드에 색인을 만들었지 만 이것이이 문제를 처리하는 올바른 방법인지는 확실하지 않습니다.
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());
}
스크립트를 표시하십시오. – yacc
단어 필드에 고유 색인을 추가하려고 시도 했습니까? –