spring data - Mongodb - findBy 嵌套对象的方法 [英] spring data - Mongodb - findBy Method for nested objects

查看:23
本文介绍了spring data - Mongodb - findBy 嵌套对象的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个域对象,

@Document
public class PracticeQuestion {

     private int userId;
     private List<Question> questions;

// Getters and setters
}

@Document
public class Question {

     private int questionID;
     private String type;

// Getters and setters
}

我的 JSON 文档是这样的,

My JSON doc is like this,

{
    "_id" : ObjectId("506d9c0ce4b005cb478c2e97"),
    "userId" : 1,
    "questions" : [
        {
            "questionID" : 1,
            "type" : "optional"

         },
        {
             "questionID" : 3,
             "type" : "mandatory"
        }
    ]
}

我要根据userId和questionId更新类型",所以我在自定义Repository接口里面写了一个findBy查询方法,

I have to update the "type" based on userId and questionId, so I have written a findBy query method inside the custom Repository interface,

public interface CustomRepository extends MongoRepository<PracticeQuestion, String> {

    List<PracticeQuestion> findByUserIdAndQuestionsQuestionID(int userId,int questionID);       
}

我的问题是,当我使用 userId 为 1 和 questionID 为 3 执行此方法时,它会返回整个问题列表,而与 questionID 无关.查询方法名称是否有效或者我应该如何编写嵌套对象的查询.

My problem is when I execute this method with userId as 1 and questionID as 3, it returns the entire questions list irrespective of the questionID. Is the query method name valid or how should I write the query for nested objects.

感谢您的任何建议.

推荐答案

只需在该方法上使用 @Query 注释即可.

Just use the @Query annotation on that method.

public interface CustomRepository extends MongoRepository<PracticeQuestion, String> {

    @Query(value = "{ 'userId' : ?0, 'questions.questionID' : ?1 }", fields = "{ 'questions.questionID' : 1 }")
    List<PracticeQuestion> findByUserIdAndQuestionsQuestionID(int userId, int questionID);

}

通过添加 @Query 注释的 fields 部分,您是在告诉 Mongo 只返回文档的该部分.但请注意,它仍然以相同的格式返回整个文档 - 只是丢失了您未指定的所有内容.所以你的代码仍然需要返回 List<PracticeQuestion> 并且你必须这样做:

By adding the fields part of the @Query annotation, you are telling Mongo to only return that part of the document. Beware though, it still returns the entire document in the same format - just missing everything you did not specify. So your code will still have to return List<PracticeQuestion> and you will have to do:

foreach (PracticeQuestion pq : practiceQuestions) {
    Question q = pq.getQuestions().get(0); // This should be your question.
}

这篇关于spring data - Mongodb - findBy 嵌套对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆