Can i use mongoTemplate or other class/interface to find one/several column(s) in a collection?
For example, if i want to get only the name from collection: users(name, password, age, email) , how could i do?
You can specify the fields returned by the query with Query.fields() method.
So in your case, assuming that user collection is mapped to User class the query could look like this:
Query query =new Query(whatever criteria you have);
query.fields().include("name");
List<User> list = template.find(query, User.class);
Another way would be o extends a MongoRepository and specify fields qith Queryannotation:
public interface UserRepository extends MongoRepository<User, String> {
@Query(fields="{ 'name' : 1}")
List<User> findUserNames();
}
findUserNames should return User instances with only name and id fields initialized.
edit
By the looks of it spring-data-mongo doesn't have a converter to String registered so you have to either retrieve User with all the fields except the ones included in the query set to null or create and register a converter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With