spring data - Mongodb - findBy Method for nested objects

前端 未结 3 1265
一个人的身影
一个人的身影 2020-12-01 06:41

I have two domain objects,

@Document
public class PracticeQuestion {

     private int userId;
     private List questions;

// Getters and s         


        
3条回答
  •  孤独总比滥情好
    2020-12-01 07:13

    You need to use Mongo Aggregation framework :

    1) Create custom method for mongo repository : Add custom method to Repository

    UnwindOperation unwind =  Aggregation.unwind("questions");
    MatchOperation match = Aggregation.match(Criteria.where("userId").is(userId).and("questions.questionId").is(questionID));
    Aggregation aggregation = Aggregation.newAggregation(unwind,match);
    AggregationResults results = mongoOperations.aggregate(aggregation, "PracticeQuestion",
                    PracticeQuestionUnwind.class);
    return results.getMappedResults();
    

    2) You need to cretae a class(Because unwind operation has changed the class structure) like below :

    public class PracticeQuestionUnwind {
        private String userId;
        private Question questions;
    

    This will give you only those result which matches the provide userId and questionId

    Result for userId: 1 and questionId : 111 :

    {
        "userId": "1",
         "questions": {
                    "questionId": "111",
                    "type": "optional"
                 }
     }
    

提交回复
热议问题