[英]Spring MongoDB data can not fetch @DBRef objects with “find” query
[英]Spring Data MongoDb - Find All nested objects
假設我有以下兩個文檔:
@Document
public class Exam {
private int examId;
private List<Question> questions;
和
public class Question {
private int questionId;
private String question;
我需要編寫一個“ findAll”,使用MongoRepository或Java中的某些其他方式,為某個“ Exam”對象(examId == n)返回所有問題的列表(或者理想情況下,在Question對象中僅返回“ question”字符串) 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,但是您可以定義更合適的類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.