Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring mongoTemplate find special column

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?

like image 470
user1755541 Avatar asked Dec 06 '25 02:12

user1755541


1 Answers

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.

like image 68
soulcheck Avatar answered Dec 08 '25 15:12

soulcheck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!