让我们说出这两份文件:
@Document
public class Exam {
private int examId;
private List<Question> questions;
和
public class Question {
private int questionId;
private String question;
我需要写一个&#39; findAll&#39;返回某个&#39;考试的所有问题列表(或理想情况下只有问题对象中的问题&#39;字符串)。对象(examId == n)使用MongoRepository或者使用Spring Data MongoDb在Java中使用其他方法,我该怎么做?
{
"_id" : ObjectId("xyz"),
"_class" : "com.xxx.Exam",
"examId" : 1,
"questions" : [
{"questionId" : 1, "question" : "xyz" },
{"questionId" : 2, "question" : "abc" }
]
}
答案 0 :(得分:0)
有多种方法可以做到这一点,其中一种可能是这样的:
MatchOperation match = match(new Criteria("examId").is(1));
UnwindOperation unwind = unwind("questions");
ProjectionOperation project = project().andExclude("_id").and("questions.question").as("question");
Aggregation aggregation = newAggregation(match, unwind, project);
AggregationResults<DBObject> result = mongoOperations.aggregate(aggregation, "exams", DBObject.class);
result.forEach(new Consumer<DBObject>() {
@Override
public void accept(DBObject t) {
System.out.println(t.toString());
}
});
// otuput
// { "question" : "xyz"}
// { "question" : "abc"}
此处将结果映射到DBObject,但您可以定义更合适的类。