I am using spring -data-mongodb.
I want to query the database by passing an 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;
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 request parameters.
If I transfer any of them, it should return the corresponding document with the given key or username.
My service method:
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, using the query above, it does not return the document with the specified key or username. What is wrong with my request?
This is how I make the request http: // localhost: 8080 / document / getByCategory? Key = key_one & username = ppotdar & categories = category1 & categories = category2