mercredi 15 novembre 2017

Random document in mongodb using spring boot [duplicate]

This question already has an answer here:

I am trying to retrieve random documents in mongodb through spring boot application with specific requirements and specific number of documents.Now i am getting documents as per my requirements and number of documents but not random documents. Actually i am not aware of where to add random logic in my code.Can any one know please suggest me.

Here is my Java code:

@Override
    public List getSpecificquestions(String subject,String topic,String level,String complexity,String questionType,String num) {
        int n=Integer.parseInt(num);
        Query query11 = new Query();
        query11.addCriteria(Criteria.where("subjectLists.subject").in(subject)
                .andOperator(Criteria.where("subjectLists.topicList.topic").in(topic)
                .andOperator(Criteria.where("subjectLists.topicList.levelList.level").in(level)
                .andOperator(Criteria.where("subjectLists.topicList.levelList.complexityList.complexity").in(complexity)
                .andOperator(Criteria.where("subjectLists.topicList.levelList.complexityList.questionTypeList.questionType").in(questionType)))))).limit(n);

        List<QuestionBank> userTest11 = mongoOperation.find(query11, QuestionBank.class);
        System.out.println("query11 - " + query11.toString());
        for (QuestionBank questionBank : userTest11) {
            System.out.println("userTest11 - " + questionBank);
        }

        return userTest11;
    }

This code is giving correct result based on my requirements, if i want to add random thing here where i have to invlove.

Basically in mongodb terminal to find random documents for we usually using below query.

db.questionBank.aggregate({ $sample: { size: 3 } } );




Aucun commentaire:

Enregistrer un commentaire