Search code examples
javaspringmongodbmongodb-queryspring-data-mongodb

How do I retrieve a subset of fields using Spring's MongoTemplate and Query classes?


I want to be able to execute the following console command to return all rows with only a subset of fields populated but using Spring's MongoTemplate class:

Console Command

db.person.find(null,{name:1})

MongoTemplate

mongoTemplate.find(new Query(...), Person.class)

Info on projection (subset) queries can be found in the MongoDB manual.


Solution

  • Query q = new Query();
    q.fields().include("name");
    mongoTemplate.find(q, Person.class);