给出 我正在从一组帖子中寻找 要将操作与java实现进行比较,我正在寻找以下方法的线索: 在将其翻译为mongodb查询时,这是我到目前为止所拥有的: 这将产生如下文件: 现在,我正在努力解决最终的 如何修复查询以获得预期结果? 答案 0 :(得分:1) $project等效于Java的地图:Post
类型的文档为:@Getter
@AllArgsConstructor
class Post {
String publisher;
Set<String> interests;
}
Set<Result>
,以使Result
对象看起来像:@Getter
@AllArgsConstructor
class Result {
String interestId;
String publisherId;
Long count;
}
Set<Result> buildQuery(List<Post> postList) {
return postList.stream()
.flatMap(post -> post.getInterests().stream()
.map(interest -> new AbstractMap.SimpleEntry<>(interest, post.getPublisher())))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.map(e -> new Result(e.getKey().getKey(), e.getKey().getValue(), e.getValue()))
.collect(Collectors.toSet());
}
db.posts.aggregate([
{"$unwind" :"$interestIds"},
{"$group" : {"_id": {interestId: "$interestIds", publisherId:"$publisherId"}, "count": {"$sum" : 1}}},
]);
{
"_id" : {
"interestId" : "INTEREST1",
"publisherId" : "PUBLISHER2"
},
"count" : 3.0
}
map
操作,以将其表达为预期结果,即:{
"_id" : ...
"interestId" : "INTEREST1",
"publisherId" : "PUBLISHER2"
"count" : 3.0
}
1 个答案:
SerialNumber