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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32108953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:03:24  来源:igfitidea点击:

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

javaspringmongodbspring-dataspring-data-mongodb

提问by richersoon

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

我们如何在 Spring Data Mongo 中选择特定字段。我尝试了以下操作,但从Footo得到了强制转换异常String

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;
  …
}

回答by Pankaj Mandale

You can use

您可以使用

Query query = new Query();

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

回答by Oliver Drotbohm

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

MongoDB 只为标准查询返回 JSON 文档。仍然可以通过返回一个List<Foo>. 该fields物业@Query正在返回将导致只有字段设置为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 Fooinstance from being handed to save(…)in turn.

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

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

另一种选择是使用聚合框架,但这涉及更多。

回答by Nikhil Kumar K

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

弹簧数据文档中的更多信息

回答by Ajit Nikam

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

如果 path=Path3,下面的查询将返回 Foo 对象

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

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

我们需要使用 fieldName:1 指定必填字段,如果不需要,则使用 0 指定它。