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));
提前致谢,
最佳答案
与查询无关。 解决方案 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
令人惊讶的是,第二种方法对我很有效......!
关于java - 如何忽略mongodb条件查询中的空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48962724/