Description
Hi, we have a bunch of APIs that allow our users to specify a comma-separated list of fields that they want to receive back from the API response, which lowers our network bandwidth usage:
@GetMapping("/books")
public List<Book> getAllBooks(
@RequestParam(defaultValue = "") Set<String> fieldsToInclude //Set removes duplicate fields
) {
return bookDAO.getBooks(fieldsToInclude)
}
Currently, spring-data allows us to project fields on a query using the include()
and exclude()
methods. However, the include()
method only accepts String
or String...
. Thus, we're forced to add code to convert our Lists into String arrays just to satisfy the include()
function's signature.
public List<Book> getBooks(Collection<String> fieldsToInclude) {
var query = new Query();
query.fields().include(fieldsToInclude.toArray(new String[0]));
query.with(Sort.by("date").descending());
return mongoTemplate.find(query, Book.class);
}
This adds complexity and maintenance overhead even though Collection
is the more flexible and more common data structure to use in Java code over String[]
.
So, I would like to propose adding a new version of include
and exclude
that accepts Collection
so that we can directly use modern Collection
implementors (List, Set, etc) for these methods instead of being forced to convert them to primitive String[]
first?
The implementation would be pretty simple, so this should be an easy upgrade that would greatly improve the public API of spring-data-mongo Query
objects to make them more flexible and usable:
public Field include(Collection<String> fields) {
Assert.notNull(fields, "Keys must not be null!");
for (String key : fields) {
criteria.put(key, 1);
}
return this;
}
// similar for exclude
(I can raise a PR for this if that's easier for the spring team)