简体   繁体   English

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

[英]How to reference an embedded document in mongodb using SpringData

How can I reference an embedded document in mongodb ? 如何在mongodb中引用嵌入式文档?
Imagine, I have a Question and AnswerOptions documents and I want to save the user answer to UserAnswer document. 想象一下,我有一个Question and AnswerOptions文档,我想将用户答案保存到UserAnswer文档中。
Now, how should I point to that option in AnswerOptions document which is embedded? 现在,我该如何指向嵌入的AnswerOptions文档中的该选项?
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: 现在,您可以定义一个MongoRepository来查询问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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