简体   繁体   中英

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 .

Query q = new Query();
q.fields().include("name");
mongoTemplate.find(q, Person.class);
mongoTemplate.getCollection(COLLECTION).find(null, new BasicDBObject(FIELD, "1"))

您可以使用:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM