【问题标题】:Spring Mongodb $filter nested object using CriteriaDefinitionSpring Mongodb $filter 使用 CriteriaDefinition 的嵌套对象
【发布时间】:2019-07-31 19:19:40
【问题描述】:

我有以下课程

@Document("artists")
public class Artist {
    private String name;
    private List<Album> discography;
    // Getters and Setters
}

public class Album {
    private String title;
    private Instant releaseDate;
    // Getters and Setters
}

我的目标是使用 Spring 数据 mongodb 编写一个聚合函数,这将允许我首先通过 name 找到一个 Artist,然后查看关联的 List&lt;Album&gt; 并根据提供的日期范围过滤其内容。然后它应该返回一个List&lt;Album&gt;,其中包含该日期范围内的所有Album 实例。

我遇到的主要问题是提供了一个CriteriaDefinition 的实例,我需要使用它的内容构造聚合和$filter 条件。

// A CriteriaDefinition gets passed into this method
// which contains various criteria to search on

Aggregation agg = Aggregation.newAggregation(
    Aggregation.match(criteriaDefinition), //This returns the correct Artist, but with all Album objects
    Aggregation.project()
        .and(filter("album.discography")
        .as("discography")
        .by( //how do use a CriteriaDefinition here? )
    .as("albums")
);

List<Album> albums = mongoTemplate
            .aggregate(agg, Artist.class, Album.class);
return albums;

甚至可以过滤CriteriaDefinition吗?

【问题讨论】:

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


    【解决方案1】:

    您可以使用unwind 运算符来匹配子文档。例如,我过滤了名称为“foobar”的艺术家,并返回了 releaseDate 大于现在的专辑。 请尝试:

    Aggregation aggregation = newAggregation(
                    match(where("name").is("foobar")),
                    unwind("discography"),
                    match(where("discography.releaseDate").gt(new Date())));
    
    AggregationResults<Album> results = mongoTemplate.aggregate(aggregation, Artist.class, Album.class);
    List<Album> albums = results.getMappedResults();
    

    【讨论】:

      猜你喜欢
      • 2020-07-01
      • 2016-03-05
      • 2012-09-25
      • 2016-12-19
      • 1970-01-01
      • 2017-06-26
      • 2018-03-27
      • 2016-04-19
      • 2016-06-25
      相关资源
      最近更新 更多