Spring Data Mongo @Aggregation 中的动态匹配标准

问题描述 投票:0回答:1

我们有一个具有不同属性的文档集合,我们将它们称为实体。目前我们正在使用 Spring Data Mongo Aggregation API 来构建我们的聚合。本质上,这就是我们正在做的事情:

public class EntityRepository<Entity, String> extends SimpleMongoRepository {

    public Page<Entity> findEntities(Pageable pageable, Map<String, Pattern> filters) {
        // ... handle empty/null filters and paging


        // build up criteria from provided filters
        Criteria criteria = new Criteria()
        for (Entry<String, Pattern> filter : filters.entrySet()) {
            criteria = criteria.and(filter.getKey).regex(filter.getValue);
        }

        Aggregation aggregation = Aggregation.newAggregation(
            match(criteria),
            sort(sort),
            skip(pageable.getOffset()),
            limit(pageable.getPageSize())
        );

        // ... run aggregation using the MongoOperations
        // ... return using PageableExecutionUtils
        
    }

}

不幸的是,我们无法提前知道可能会出现哪些过滤器。因此查询必须是动态的。

我想要的是以下内容。这可能吗?我想它必须迭代过滤器参数的映射。

public interface EntityRepository<Entity, String> extends MongoRepository {

    // TODO have a match conditional for each key / value pair in filters param
    @Aggregation(pipeline = {
       "{ $match : { $and: [] } } "
    })
    @Meta(allowDiskUse = true)
    public Page<Entity> findEntities(Pageable pageable, Map<String, Pattern> filters);

}

java mongodb spring-boot spring-data-mongodb
1个回答
0
投票

使用 MongoTemplate 或 MongoOperations 代替聚合注释。 注入其中之一并使用过滤器地图进行查询。

List<Criteria> criterias = new ArrayList();

//create your queries from your map something like
//criterias.add(where(entry.getKey()).eq(entry.getValue()));


mongoOperations.find(new Criteria().andOperator(criterias));
© www.soinside.com 2019 - 2024. All rights reserved.