dgiaig
dgiaig

Reputation: 221

Springdata: mongodb find query with optional "criterias"

Houston, I have a problem (hi all!).

I'm using springdata's @query annotation, and I need to perform a find query with some criterias.

Assuming that my collection object is like:

and my search criteria object is

i need to search in the collection for a document that meet my criteria.

The problem is that the search criteria are not obligatory, so I can have some null params (for example, sometimes I have to find document with a specific code and date, sometimes with a specific email, etc. etc. ) so I started to googling for a solution.

I read about the $or and $and operator (i'm sorry for the and repetition), I tried to implement a solution (i know, do or do not, there is no try) but I'm very confused about how to get it work.

The currrent situation is :

@Query(value = "{date: { $exists: false }, key: ?0 , $or : [{$or : [{$where: '?1==null'}, {code : ?1}]},{$or : [{$where: '?2==null'}, {status : ?2}]}]}")
public Page<Notification> findByNotificationCriteria(Pageable page, String key, String code, String status);

(i tried also with $and operator at the beginning)

but the results are not what I expect.

I'm doing something wrong or it's just a springdata problem?

Thanks.

Upvotes: 1

Views: 2171

Answers (1)

Zarathustra
Zarathustra

Reputation: 2943

I know that is not a real solution.

  1. You could use query-dsl to accomplish that. Here a nice tutorial: http://www.littlelostmanuals.com/2011/09/spring-mongodb-type-safe-queries.html
  2. (Wait) Also look at this Jira Issue, if the support for such things is in spring-jpa it will be in mongo very soon. https://jira.spring.io/browse/DATAJPA-209
  3. You could also use the MongoTemplate class directly OR
  4. Extend your repository in a matter of spring-data. http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

In your case I would go with query-dsl, since you have to do it once and covered all repositories. (1)

Note: To make it a bit better, do not use com.mysema.query.apt.QuerydslAnnotationProcessor instead use org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor for that you don't have to use query-dsl's @QueryEntity ;)

If you just have a single repository where you have optional parameters, consider to subclass the repository(4)

Upvotes: 1

Related Questions