0

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"
        }        
        ]

    }

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.