JARC
JARC

Reputation: 5328

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.

Upvotes: 23

Views: 38459

Answers (4)

M. Justin
M. Justin

Reputation: 21239

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");

Upvotes: 2

Damian Szuta
Damian Szuta

Reputation: 11

You can use:

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

Upvotes: 1

JARC
JARC

Reputation: 5328

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

Upvotes: 61

dan andrei zaharia
dan andrei zaharia

Reputation: 41

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

Upvotes: 4

Related Questions