用运算符查询mongo或

时间:2018-12-12 15:07:25

标签: mongodb spring-data-jpa spring-data spring-data-mongodb

如果parameter为null,则获取所有对象;如果parameter不为null,则获取带有参数的对象。 我有查询:

@Query("{$and : [{$or : [ { $where: '?0 == null' } , { topic : ?0 }]}] }")
    List<Event> find(Topic topic);

在运行带有topic = Topic.SPORT的方法的地方,我得到了:

  

引发异常[请求处理失败;嵌套异常为   org.springframework.data.mongodb.UncategorizedMongoDbException:查询   失败,错误代码16722和错误消息“ ReferenceError:SPORT”   未定义”在服务器localhost:27017上;嵌套异常为   com.mongodb.MongoQueryException:查询失败,错误代码为16722   和服务器上的错误消息“ ReferenceError:未定义SPORT”   localhost:27017]的根本原因

但是如果我使用topic = null来运行此方法,那么我将获得所有对象(是真的)

我重构此方法,如下所示:

@Query("{$and : [{$or : [ { $where: '\"?0\" == null' } , { topic : ?0 }]}] }")
    List<Event> find(Topic topic);

我可以使用参数topic = Topic.SPORT来获取对象,但是无法获取topic = null时得到的所有对象,而我的列表为空。  我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

要解决您的问题,您应该先检查一下。 1.查询主题 话题:?0 2.如果为null〜> true $ where:'\“?0 \” == null' 这是您的方法,但是我们还有其他方法可以在mongodocument(https://docs.mongodb.com/manual/tutorial/query-for-null-fields/)中找到:

db.inventory.find( { item : { $type: 10 } } )
db.inventory.find( { item : { $exists: false } } )

$ type:使用了10次,您将该字段保存为null 和$ exit来检查此字段是否可用。

在那之后,我们得到了$ or的组合。 希望你做得好