Spring MongoDB:Criteria方法非静态访问

时间:2016-04-26 13:31:42

标签: java mongodb aggregation-framework spring-mongo

我正在使用AggregationCriteria编写动态MongoDB查询。

Aggregation aggregation;
AggregationResults<DataContentResult> result;
List<DataContentResult> theResult;
try {
    aggregation = Aggregation.newAggregation(
                buildMatchCriteriaForAggregation(publisherId, filter)
                , buildGroupOperationForAggregation());

    result = mongoTemplate.aggregate(aggregation, DataContent.class, DataContentResult.class);
    theResult = result.getMappedResults();

} catch (Exception e) {
    e.printStackTrace();
}

@SuppressWarnings("static-access")
private AggregationOperation buildMatchCriteriaForAggregation(Integer publisherId, Filter filterCriteria){
    Criteria criteria = new Criteria();
    criteria.where("publisherId").is(publisherId);

    if (filterCriteria.getTa() != null) criteria.where("type").is(filterCriteria.getTa());
    if (filterCriteria.getPlz() != null) criteria.where("zip").is(ilterCriteria.getPlz());
    if (filterCriteria.getTbVerlag() != null) criteria.where("tbVerlagNr").is(filterCriteria.getTbVerlag());

    return Aggregation.match(criteria);
}

现在我知道我应该以{{1​​}}之类的静态方式访问Criteria个方法。但在我的情况下,我需要根据其可用性指定我的Criteria.where("something").is("something")标准。因此我必须如上所述。这不起作用,Filter对象由于某种原因每次都会变空。

在这种情况下,建议使用哪种替代方法?还是我做错了什么?

1 个答案:

答案 0 :(得分:2)

好吧,答案结果很简单如下:

Criteria criteria = new Criteria();

criteria = criteria.where("publisherId").is(publisherId);
if(<condition>) criteria = criteria.orOperator(
                       Criteria.where("something").is("something"));