Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

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.

@user1755541 not sure if mongo has the converter registered for DBObject to String, but you can try that easly (just change User to String). You certainly can get a Map with only name element set. – soulcheck Oct 19, 2012 at 7:47

Use Google Guava to solve your problem. Of course, You can use standard foreach construction, but in my opinion Guava is faster to implement and well tested.

Here is the link with good example http://www.leveluplunch.com/java/tutorials/002-transform-objects-with-guava/

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.