代码之家  ›  专栏  ›  技术社区  ›  Naman

计算关系的总数并将其映射到结果

  •  0
  • Naman  · 技术社区  · 6 年前

    给予 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());
    }
    

    在将其转换为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
    }
    

    0 回复  |  直到 6 年前
        1
  •  1
  •   mickl    6 年前

    $project

    db.posts.aggregate([
        {"$unwind" :"$interestIds"},
        {"$group" : {"_id": {interestId: "$interestIds", publisherId:"$publisherId"}, "count": {"$sum" : 1}}},
        {"$project":{ _id: 0, interestId: "$_id.interestId", publisherId: "$_id.publisherId", count: 1 }}
    ]);
    
    推荐文章