如何在Spring Data MongoDB中仅返回查询的特定字段?

我们如何在Spring Data Mongo中选择特定字段。 我尝试了以下但是我从FooString得到了exception。

使用@Query

 @Query(value="{path : ?0}", fields="{path : 0}") String findPathByPath(String path); 

@Query

 String findPathByPath(String path); 

这是文档模型

 @Document(collection = "foo") public class Foo { String name, path; … } 

MongoDB仅返回标准查询的JSON文档。 您仍然可以通过返回List来实现您想要看到的内容。 @Queryfields属性将仅返回设置为1的字段。

 @Query(value="{ path : ?0}", fields="{ path : 0 }") List findByPath(String path); 

我们通常建议为此引入专用的DTO,以便防止部分填充的Foo实例依次被传递给save(…)

另一个选择是使用聚合框架,但更复杂。

您可以使用

 public interface PersonRepository extends MongoRepository @Query(value="{ 'firstname' : ?0 }",fields="{ 'firstname' : 1, 'lastname' : 1}") List findByThePersonsFirstname(String firstname); } 

有关spring数据文档的更多信息

您可以使用

 Query query = new Query(); query.fields().include("path");