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

时间:2022-09-11 16:44:31

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

如何在Spring数据Mongo中选择特定的字段。我尝试了以下操作,但是从Foo到String我得到了cast exception。

Using @Query

使用@Query

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

Non @Query

非@Query

String findPathByPath(String path);

Here is the document model

这是文档模型。

@Document(collection = "foo")
public class Foo  {

  String name, path;
  …
}

3 个解决方案

#1


13  

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.

MongoDB只返回标准查询的JSON文档。您希望看到的结果可以通过仍然返回一个 列表来实现。@Query的fields属性将只返回设置为1的字段。

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

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.

我们通常建议引入专门的DTO,这样您就可以防止部分填充的Foo实例被依次传递到save(…)。

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

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

#2


7  

You can use

您可以使用

public interface PersonRepository extends MongoRepository<Person, String>

  @Query(value="{ 'firstname' : ?0 }",fields="{ 'firstname' : 1, 'lastname' : 1}")
  List<Person> findByThePersonsFirstname(String firstname);

}

More information in spring data documentation

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

#3


5  

You can use

您可以使用

Query query = new Query();

查询查询=新查询();

query.fields().include("path");

query.fields()其中包括(“路径”);

#1


13  

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.

MongoDB只返回标准查询的JSON文档。您希望看到的结果可以通过仍然返回一个 列表来实现。@Query的fields属性将只返回设置为1的字段。

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

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.

我们通常建议引入专门的DTO,这样您就可以防止部分填充的Foo实例被依次传递到save(…)。

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

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

#2


7  

You can use

您可以使用

public interface PersonRepository extends MongoRepository<Person, String>

  @Query(value="{ 'firstname' : ?0 }",fields="{ 'firstname' : 1, 'lastname' : 1}")
  List<Person> findByThePersonsFirstname(String firstname);

}

More information in spring data documentation

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

#3


5  

You can use

您可以使用

Query query = new Query();

查询查询=新查询();

query.fields().include("path");

query.fields()其中包括(“路径”);