Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.piotr.apollo.service; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import java.util.ArrayList; import java.util.List; import org.bson.Document; import org.bson.types.ObjectId; import org.piotr.apollo.database.mongoDB; import org.piotr.apollo.model.Answer; import org.piotr.apollo.model.Question; import org.piotr.apollo.model.Test; /** * * @author Leniwiec */ public class QuestionService { private final String questionCollection = "questionCollection"; AnswerService answerService = new AnswerService(); mongoDB db = new mongoDB(); public ObjectId addQuestion(Question question, ObjectId testId) { MongoCollection collection = db.getCollection(questionCollection); Document objInsert = new Document(); objInsert.put("number", question.getNumber()); objInsert.put("question", question.getQuestion()); objInsert.put("test_id", testId); collection.insertOne(objInsert); return (ObjectId) objInsert.get("_id"); } public List<Question> getQuestion(ObjectId testId) { MongoCollection collection = db.getCollection(questionCollection); List<Question> questionList = new ArrayList<Question>(); Document findQuestions = new Document(); findQuestions.append("test_id", testId); FindIterable iterable = collection.find(findQuestions); MongoCursor<Document> cursor = iterable.iterator(); while (cursor.hasNext()) { Document document = cursor.next(); Question question = new Question(); question.setTest_id(testId); question.setId(document.get("_id").toString()); question.set_Id((ObjectId) document.get("_id")); question.setQuestion(document.getString("question")); question.setNumber(document.getInteger("number")); List<Answer> answersList = answerService.getAnswers(question.get_Id()); question.setAnswersList(answersList); questionList.add(question); } return questionList; } }