简体   繁体   中英

How to query documents with null values MongoRepository Spring Data MongoDB

I couldn't initialise the value to be false in Spring Data MongoDB, so in my query, I want to search documents with field set to false or null.

The following snippet doesn't seem to work:

@RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
Order findByIdAndIsActiveFalseOrIsActiveNull(@Param("id"))

I'm not sure you can achieve such query using Spring data method name. Since your query will be evaluated as _id == "id" AND isActive == false OR isActive == null and not _id == "id" AND ( isActive == false OR isActive == null ) .

If by chance isActive can only be true , false or null , you could try

@RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
Order findByIdAndIsActiveNot(@Param("id"), true)

Otherwise, you will need to use other query method provided by Spring data mongodb such as MongoTemplate helper class or @Query annotation.

@Query annotation

@RestResource(rel = "findInactiveOrders", path = "findInactiveOrders")
@Query("{$and: [{'_id': :#{#id}}, $or: [{ 'isActive':false}, {'isActive': null}]]}")
Order findByIdAndIsActiveNot(@Param("id"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM