diff --git a/questionGenerator/src/main/java/Main.java b/questionGenerator/src/main/java/Main.java index 45e9bc0b..41a0d999 100644 --- a/questionGenerator/src/main/java/Main.java +++ b/questionGenerator/src/main/java/Main.java @@ -1,5 +1,8 @@ package main.java; +import java.util.ArrayList; +import java.util.List; + import main.java.questionGenerator.QuestionGenerator; import main.java.questionGenerator.question.Question; import main.java.questionGenerator.question.QuestionType; @@ -33,12 +36,17 @@ public static void main(String[] args) { } private static void run(QuestionGenerator qg, QuestionType type) { + List questionJSONList = new ArrayList<>(); + + //Populate JSON list here for(int i=0; i<3; i++) { Question question = qg.generateQuestion(type); question.setNumber(i); - QuestionRepository.getInstance().insertOne(question.getJSON().toString()); + questionJSONList.add(question.getJSON().toString()); System.out.println(question.getJSON().toString()); } + + QuestionRepository.getInstance().insert(questionJSONList); } } diff --git a/questionGenerator/src/main/java/questionGenerator/repository/QuestionRepository.java b/questionGenerator/src/main/java/questionGenerator/repository/QuestionRepository.java index 3aee679d..b9ec14aa 100644 --- a/questionGenerator/src/main/java/questionGenerator/repository/QuestionRepository.java +++ b/questionGenerator/src/main/java/questionGenerator/repository/QuestionRepository.java @@ -4,6 +4,12 @@ import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.InsertManyOptions; +import com.mongodb.client.result.InsertManyResult; + +import java.util.ArrayList; +import java.util.List; + import org.bson.Document; public class QuestionRepository { @@ -22,7 +28,7 @@ public static QuestionRepository getInstance(){ return questionRepository; } - public boolean insertOne(String questionJSON){ + public boolean insert(String questionJSON){ try (MongoClient mongoClient = MongoClients.create(dbConnectionString)) { MongoDatabase database = mongoClient.getDatabase("questions"); @@ -35,5 +41,25 @@ public boolean insertOne(String questionJSON){ return false; } } + + public boolean insert(List questionJSONList){ + try (MongoClient mongoClient = MongoClients.create(dbConnectionString)) { + MongoDatabase database = mongoClient.getDatabase("questions"); + + MongoCollection collection = database.getCollection("questions"); + + List documents = new ArrayList<>(); + for (String questionJSON : questionJSONList) { + documents.add(Document.parse(questionJSON)); + } + + InsertManyResult result = collection.insertMany(documents, new InsertManyOptions().ordered(false)); //unordered write + // Check if all documents were inserted successfully + return result.wasAcknowledged() && result.getInsertedIds().size() == documents.size(); + } catch (Exception e) { + System.out.println(e); + return false; + } + } } \ No newline at end of file