如何在MongoDB条件查询中忽略空参数。

5
 List<Property> properties;
 Criteria criteria = new Criteria();

criteria.andOperator(
            Criteria.where("published").is(true),
            Criteria.where("location.district").regex(model.getLocation(),"i").orOperator(Criteria.where("location.city").exists(true).regex(model.getLocation(),"i")),
            Criteria.where("basicInfo.propertyType").is(model.getPropertyType()),
            Criteria.where("priceInfo.price").gte(prices[0]).lte(prices[1]),
            Criteria.where("bedspace").gte(model.getAdult()).orOperator(Criteria.where("bedspace").gte(model.getChild())),
            Criteria.where("unavailableDates").ne(model.getCheckinDate()).andOperator(Criteria.where("unavalibleDates").ne(model.getCheckoutDate())),
            Criteria.where("location.coords").within(box));

    Query query = new Query(criteria);
    properties = mongoTemplate.find(query, Property.class);

我的代码基本上是这样工作的。我的目标是创建一个搜索机制,用户将输入位置信息开始搜索,然后通过添加额外的过滤器来自定义搜索。我将它们放在andOperator中,因为我希望此搜索针对位置参数进行指定。

例如:您搜索德国,然后添加价格过滤器,例如在0-100之间,那么搜索应该执行以下操作: 返回从德国出发价格在0-100之间的房屋

但是有一个问题。 当用户输入位置查询时,模型只包含位置参数,这意味着查询模型中的其他参数为空,当它进入andOperator时,它会产生空指针异常。我希望它忽略空参数并继续处理其他参数。我该如何实现这一点?

我尝试添加ne(null)字段,但没有帮助

 Criteria.where("location.coords").ne(null).within(box));

提前感谢您的帮助。

3个回答

2

这与查询无关。 解决方案-1:你只需要告诉Jackson Mapper在类级别上排除所有空值。

@JsonInclude(Include.NON_NULL)
public class MyDto {

private String myfield;

// Getter and Setter   
}

解决方案2:您只需在您的.yml或.properties文件中添加以下属性即可。
jackson:
  default-property-inclusion: non-null

令人惊讶的是,第二种方法对我非常有效.....!


0

你需要像这样改进你的查询:

db.getCollection('criteria').find({
 'location.coords': {
     $ne: null
 }
});

0

只需将您的查询更改为以下内容,然后尝试这个。

Query query = new Query();
Criteria criteria = new Criteria();
List<Criteria> orCriterias = new ArrayList<>();
if( published != null) {    
  orCriterias.add(Criteria.where("published").is(published)));
}
... so on for other fields
criteria.orOperator(orCriterias.toArray(new Criteria[orCriterias.size()]));
query.addCriteria(criteria);
List<Property> recordsList = mongoTemplate.find(query, Property.class, 

"collecion name");


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接