【问题标题】:Spring data mongodb - empty result while trying aggregate and projectSpring data mongodb - 尝试聚合和项目时为空结果
【发布时间】:2018-05-11 17:46:23
【问题描述】:

我在使用 mongooperations 进行投影和分页时遇到了一些麻烦。我总是得到空的结果。查询条件在没有聚合的情况下工作正常。我尝试了相同的代码,没有分页(跳过和限制),也没有排序,但我仍然得到空结果。

我的代码:

public List<ProfileBasic> findAllActiveUsersByGenderAndAgeBetweenProjectedPage(Gender gender, int fromAge, int toAge, int pageSize, int page) {

        Criteria criteria = Criteria.where("gender").is(gender).and("confirmed").is(true)
                .and("dateOfBirth").lte(LocalDate.now().minusYears(fromAge))
                .gte(LocalDate.now().minusYears(toAge));
        MatchOperation match = Aggregation.match(criteria);
        ProjectionOperation  project = Aggregation.project()
                .and("id").as("id")
                .and("name").as("name")
                .and("lastName").as("lastName")
                .and("gender").as("gender")
                .and("dateOfBirth").as("dateOfBirth")
                .and("lastVisit").as("lastVisit");
        SkipOperation skip = new SkipOperation(pageSize*(page-1));
        LimitOperation limit = new LimitOperation(pageSize);
        SortOperation sort = new SortOperation(new Sort(Sort.Direction.DESC, "lastVisit"));
        Aggregation aggregate = Aggregation.newAggregation(project, match, skip, limit, sort);
        return operations.aggregate(aggregate, User.class, ProfileBasic.class).getMappedResults();
    }

我将不胜感激。

【问题讨论】:

    标签: java mongodb spring-boot spring-data-mongodb


    【解决方案1】:

    当我们在 MongoDB 中进行聚合时,数据是分阶段处理的,一个阶段的输出作为下一个阶段的输入提供。

    在我的代码中,第一阶段是项目而不是匹配(查询):

    Aggregation aggregate = Aggregation.newAggregation(project, match, skip, limit, sort);
    

    这就是为什么它不起作用。

    我改成:

    Aggregation aggregate = Aggregation.newAggregation(match, skip, limit, project, sort);
    

    现在它可以正常工作了。

    【讨论】:

      猜你喜欢
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      相关资源
      最近更新 更多