【发布时间】:2021-01-16 22:30:25
【问题描述】:
我有以下代码,getRawResult 和 getMappedResult 的答案不同。我想知道如何在 mappedResults 中包含 user 和 place 对象。
// This methd searches the given string in reviews of the given country
MatchOperation matchRegion = Aggregation.match(Criteria.where("Country").is("Germany"));
//To match the review
TextCriteria criteria = TextCriteria.forDefaultLanguage().matchingAny(text);
MatchOperation match = Aggregation.match(criteria);
GroupOperation group = Aggregation.group("place.place_name").push("$$ROOT").as("reviews").sum("textScore")
.as("score");
ProjectionOperation project = Aggregation
.project("some_point", "place", "user", "date")
.andExpression("{$meta: \"textScore\"}").as("textScore");
SortOperation sortByScore = Aggregation.sort(Sort.Direction.DESC, "score");
Aggregation aggregation = Aggregation.newAggregation(match,Aggregation.lookup("place","placeId","_id","place"),
Aggregation.unwind("place"),Aggregation.lookup("user","userId","_id","user"),
Aggregation.unwind("user") , matchRegion, project, group, sortByScore);
AggregationResults<ReviewAggrResults> results = mongoTemplate.aggregate(aggregation,
mongoTemplate.getCollectionName(Review.class), ReviewAggrResults.class);
List<ReviewAggrResults> result = results.getMappedResults();
Object object = mongoTemplate.aggregate(aggregation, Review.class, Object.class).getRawResults();
Print.print("result object rawResults", object);
Print.print("result reviewaggrresult: ", result);
使用上面的代码,getRawResults 和 ReviewAggrResult 的打印结果如下:
原始结果:
{
"results" : [ {
"_id" : "ibis Heidelberg, Willy-Brandt-Platz 3, 69115 Heidelberg, Germany",
"reviews" : [ {
"_id" : {
"timestamp" : 1610817567,
"date" : 1610817567000
},
"some_point" : "something",
"date" : "Sat Jan 16 18:19:27 CET 2021",
"place" : {
"_id" : {
"timestamp" : 1610817567,
"date" : 1610817567000
},
"place_name" : "ibis Heidelberg, Willy-Brandt-Platz 3, 69115 Heidelberg, Germany",
"country" : "Germany",
},
"user" : {
"_id" : {
"timestamp" : 1610817549,
"date" : 1610817549000
},
"firstname" : "test1first",
"lastname" : "test1last",
},
"textScore" : 5.25
} ],
"score" : 5.25
} ],
"ok" : 1.0
}
映射结果:
[ {
"reviews" : [ {
"id" : "6003201f98afbc730e4f58eb",
"some_point" : "something",
"placeId" : null,
"userId" : null,
"date" : "Sat Jan 16 18:19:27 CET 2021",
"textScore" : 5.25
} ],
"id" : "ibis Heidelberg, Willy-Brandt-Platz 3, 69115 Heidelberg, Germany",
"userId" : null,
"user" : null,
"score" : 5.25
} ]
为什么它们不同?原始结果是正确的,但是当它被映射时,地点和用户对象被删除。我怎样才能将它们也包含在 mappedResult 中?
【问题讨论】:
标签: java spring mongodb aggregation-framework mongotemplate