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

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

问题描述:

我们如何在Spring Data Mongo中选择特定字段。我尝试了以下但是我从 Foo 转换为 String

How can we select specific fields in Spring Data Mongo. I tried the following but I got cast exception from Foo to String.

使用 @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文档。您还可以通过返回列表< Foo> 来实现您希望看到的内容。 @Query 中的字段属性将仅返回设置为1的字段。

MongoDB only returns JSON documents for standard queries. What you'd like to see can be achieved by still returning a List<Foo>. The fields property in @Query will cause only the fields set to 1 being returned.

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

我们通常建议为此引入专用DTO,以防止部分填充 Foo 依次交给 save(...)的实例。

We usually recommend introducing a dedicted DTO for that so that you prevent the partially filled Foo instance from being handed to save(…) in turn.

另一个选项是使用聚合框架,但更多涉及。

Another option is using the aggreation framework but that's more involved.