如何在mongodb条件查询

时间:2018-02-24 12:11:57

标签: java mongodb spring-boot mongodb-query

 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中,因为我希望将此搜索指定给location参数。

例如:您搜索德国然后添加过滤器以定价,例如0-100之间,然后搜索应该行动 : 来自德国的房屋,价格在0-100之间

但是有一个问题。 当用户输入位置查询模型时,只包含位置参数,这意味着查询模型中的其他参数为空,当它进入andOperator时,它会给出空指针异常。我希望它忽略空参数并继续使用其他参数。我怎样才能做到这一点?

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

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

提前感谢,

3 个答案:

答案 0 :(得分:0)

您需要像这样改进查询:

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

答案 1 :(得分: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, 

“学院名称”);

答案 2 :(得分:0)

与查询无关。 解决方案1:您只需要告诉杰克逊映射器在类级别排除所有空值即可。

@JsonInclude(Include.NON_NULL)
public class MyDto {

private String myfield;

// Getter and Setter   
}

解决方案2:您只需在.yml或.properties文件中添加以下属性。

jackson:
  default-property-inclusion: non-null

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