Question

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.

Was it helpful?

Solution

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

OTHER TIPS

mongoTemplate.getCollection(COLLECTION).find(null, new BasicDBObject(FIELD, "1"))

You can use:

mongoTemplate.findDistinct(String field, Class<?> entityClass, Class<T> resultClass);

If the goal is to populate the standard domain object with just the subset of fields, using d.fields().include() as described in another answer is the way to go. However, often time I find having the full object is undesirable (having a partially-populated could easily mislead future developers reading the code), and I'd rather have an object with just the subset of the fields I'm retrieving. In this case, creating and retrieving a projection object with just the subset of fields works well.

Projection class

@Document("person") // Must be the same collection name used by Person
public class PersonNameOnly {
  private String name;

  public String getName() { return name; }
  public void setName(String name) { this.name = name; }
}

MongoTemplate query

mongoTemplate.find(new Query(...), PersonNameOnly.class);

If you want to use the same projection object for multiple types, you can omit the @Document declaration with the collection name from the projection object, and specify the collection name in the MongoTemplate query.

Projection class

public class NameOnly {
  private String name;

  public String getName() { return name; }
  public void setName(String name) { this.name = name; }
}

MongoTemplate query

mongoTemplate.find(new Query(...), NameOnly.class, "person");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top