如何在Spring Data MongoDB中仅返回查询的特定字段? [英] How to return only specific fields for a query in Spring Data MongoDB?

查看:1432
本文介绍了如何在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.

这篇关于如何在Spring Data MongoDB中仅返回查询的特定字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆