弹簧数据-Mongodb-嵌套对象的findBy方法 [英] spring data - Mongodb - findBy Method for nested objects
问题描述
我有两个域对象,
@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更新类型",因此我在自定义存储库界面中编写了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.
}
这篇关于弹簧数据-Mongodb-嵌套对象的findBy方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!