给予
Post
将文档键入为:
@Getter
@AllArgsConstructor
class Post {
String publisher;
Set<String> interests;
}
我想从一系列的帖子中找出
Set<Result>
以至于
Result
对象看起来像:
@Getter
@AllArgsConstructor
class Result {
String interestId;
String publisherId;
Long count;
}
java
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());
}
在将其转换为mongodb查询时,这是我迄今为止所拥有的:
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
}