简体   繁体   中英

How to reference an embedded document in mongodb using SpringData

How can I reference an embedded document in mongodb ?
Imagine, I have a Question and AnswerOptions documents and I want to save the user answer to UserAnswer document.
Now, how should I point to that option in AnswerOptions document which is embedded?
Any best practices?

{
        "_id":"1"
        "questionTitle":"Question1"
        "answerOptions":
        [
        {
            "optionTitle":"option1"
        },
        {
            "optionTitle":"option2"
        },
        {
            "optionTitle":"option3"
        }
        ]

    },
{
        "_id":"2"
        "questionTitle":"Question2"
        "answerOptions":
        [
        {
            "optionTitle":"option1"
        },
        {
            "optionTitle":"option2"
        }
        ]

    },
{
        "_id":"3"
        "questionTitle":"Question3"
        "answerOptions":
        [
        {
            "optionTitle":"option1"
        },
        {
            "optionTitle":"option2"
        }        
        ]

    }

I don't know whether my way is considered as best practice, but this is how Ido it:

public class Question {
    private String id;
    private String questionTitle;
    private List<Answer> answerOptions;
}

public class Answer {
    private String optionTitle;
}

Now you can define a MongoRepository to query for Questions:

public interface QuestionRepository extends MongoRepository<Question,String> {
    List<Question> findByAnswerOptionsOptionTitle(@Param("answerOptions.optionTitle") String option)
}

You might also find the section about queries in MongoRepositories useful: http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#repositories.query-methods.query-property-expressions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM