How to return only specific fields for a query in Spring Data MongoDB?

谁说胖子不能爱 提交于 2019-12-03 12:13:27

问题


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

Using @Query

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

Non @Query

String findPathByPath(String path);

Here is the document model

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

  String name, path;
  …
}

回答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);

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.




回答2:


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




回答3:


You can use

Query query = new Query();

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



回答4:


You can use below query to get specific fields.

@Query(fields="{path : 1}")
Foo findPathByPath(String path);

Records present in DB

{
    "name" : "name2",
    "path" : "path2"
},
{
    "name" : "name3",
    "path" : "path3"
}

Below query will return Foo object if path=Path3

{
    "name": null,
    "path": "path3"
}

we need to specify required fields with fieldName:1 and if don't require then specify it with 0.



来源:https://stackoverflow.com/questions/32108953/how-to-return-only-specific-fields-for-a-query-in-spring-data-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!