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

时间:2015-08-20 03:12:56

标签: java spring mongodb spring-data spring-data-mongodb

我们如何在Spring Data Mongo中选择特定字段。我尝试了以下操作,但是我从FooString获得了强制转换。

使用@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;
  …
}

4 个答案:

答案 0 :(得分:18)

MongoDB仅返回标准查询的JSON文档。您还可以通过返回fields来实现您希望看到的内容。 <{1}}中的@Query属性只会返回设置为1的字段。

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

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

另一种选择是使用聚合框架,但更多参与。

答案 1 :(得分:14)

您可以使用

public interface PersonRepository extends MongoRepository<Person, String>

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

}

春季数据documentation

中的更多信息

答案 2 :(得分:11)

您可以使用

Query query = new Query();

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

答案 3 :(得分:2)

您可以使用以下查询获取特定字段。

None Traceback (most recent call last):   File
"/usr/local/lib/python3.5/dist-packages/numpy/core/fromnumeric.py",
line 51, in _wrapfunc
    return getattr(obj, method)(*args, **kwds) AttributeError: 'NoneType' object has no attribute 'round'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File
"/home/pi/Downloads/Pi-tracker-master/fgroi.py", line 49, in <module>
    sketcher_rect = sketch_transform(sketcher_rect)   File "/home/pi/Downloads/Pi-tracker-master/fgroi.py", line 20, in
sketch_transform
    ...
    result = getattr(asarray(obj), method)(*args, **kwds) AttributeError: 'NoneType' object has no attribute 'rint

数据库中存在的记录

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

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

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

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