假设我有这两个文件:
@Document
public class Exam {
private int examId;
private List<Question> questions;
和
public class Question {
private int questionId;
private String question;
我需要写一个'findAll',返回一个所有问题的列表(或理想情况下只有'问题'字符串在问题对象)的某个'考试'对象(excId==n)使用MongoRepository或其他方式在Java使用Spring Data MongoDb,我该怎么做?
{
"_id" : ObjectId("xyz"),
"_class" : "com.xxx.Exam",
"examId" : 1,
"questions" : [
{"questionId" : 1, "question" : "xyz" },
{"questionId" : 2, "question" : "abc" }
]
}
有不止一种方法可以做到这一点,其中一种可能是这样的:
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,但是您可以定义更合适的类。