I am using spring-data-mongodb.
I want to query database by passing some optional parameter in my query.
I have a domain class.
public class Doc {
@Id
private String id;
private String type;
private String name;
private int index;
private String data;
private String description;
private String key;
private String username;
// getter & setter
}
My controller:
@RequestMapping(value = "/getByCategory", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON)
public Iterable<Doc> getByCategory(
@RequestParam(value = "key", required = false) String key,
@RequestParam(value = "username", required = false) String username,
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "categories") List<String> categories)
throws EntityNotFoundException {
Iterable<Doc> nodes = docService.getByCategory(key, username , categories, page, size);
return nodes;
}
Here Key and username are optional query parameters.
If I pass any one of them it should return the matching document with given key or username.
My service method is:
public Iterable<Doc> getByCategory(String key, String username, List<String> categories, int page, int size) {
return repository.findByCategories(key, username, categories, new PageRequest(page, size));
}
Repository:
@Query("{ $or : [ {'key':?0},{'username':?1},{categories:{$in: ?2}}] }")
List<Doc> findByCategories(String key, String username,List<String> categories, Pageable pageable);
But by using above query it does not returns a document with either given key or username. What is wrong in my query?
This is how I am making request http://localhost:8080/document/getByCategory?key=key_one&username=ppotdar&categories=category1&categories=category2
Filtering out parts of the query depending on the input value is not directly supported. Nevertheless it can be done using
@Query
the$and
operator and a bit of SpEL.Instead of addressing the target function via the
T(...)
Type expression writing anEvaluationContextExtension
(see: json spel for details) allows to get rid of repeating the type name over and over again.