如何使用SpringData在mongodb中引用嵌入文档

时间:2016-04-28 17:45:33

标签: java mongodb spring-data mongodb-java

如何在mongodb中引用嵌入文档?
想象一下,我有问题 AnswerOptions 文档,我想将用户答案保存到 UserAnswer 文档。
现在,我应该如何指向嵌入的 AnswerOptions 文档中的该选项? 任何最佳做法?

{
        "_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 个答案:

答案 0 :(得分:1)

我不知道我的方式是否被视为最佳做法,但这就是我的方式:

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

public class Answer {
    private String optionTitle;
}

现在您可以定义一个MongoRepository来查询问题:

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

您可能还会发现MongoRepositories中有关查询的部分很有用: http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#repositories.query-methods.query-property-expressions