Spring Mongo 数据库查询中未返回嵌套字段

Nested fields not returned in Spring Mongo DB query

我有以下两个文件:

@Document(collection = "projects")
public class Project {

    @Id
    private String id;
    private String name;
    @Indexed(unique = true)
    private String slug;

    private List<Component> components;
    private List<Feature> features;
    private List<Text> texts;

    // constructors, getters and setters omitted
}

并且:

public class Text {

    private String key;
    private String defaultText;
    private String comment;

    private String featureUsing;
    private List<String> componentsUsing;

    // constructors, getters and setters omitted

}

基本上我在一个项目中有一个文本数组。

目前这是我唯一的文件:

{
    "_class": "org.aribeiro.i18n.entities.Project",
    "_id": "5a64b8b65aa0334ada6eced6",
    "components": [
        {
            "name": "Find and Ring portal",
            "slug": "find-and-ring-portal"
        }
    ],
    "features": [
        {
            "name": "Find and Ring",
            "slug": "find-and-ring"
        }
    ],
    "name": "Project 2",
    "slug": "project-2",
    "texts": [
        {
            "comment": "This is to show the title",
            "componentsUsing": [
                "find-and-ring-portal"
            ],
            "defaultText": "Find and Ring",
            "featureUsing": "find-and-ring",
            "key": "findringportal.title"
        }
    ]
}

我只想获取符合以下过滤器的文本部分:

{'texts.key': 'findringportal.title' }

所以我在我的 TextsRepository 中配置了这个查询:

@Query(value = "{'texts.key': ?0 }", fields = "{ 'texts.key' : 1, 'texts.defaultText': 1 }")
Text findByKey(String key);

TextsRepository 是:

public interface TextsRepository extends MongoRepository<Text, String> {

    @Query(value = "{'texts.key': ?0 }", fields = "{ 'texts.key' : 1, 'texts.defaultText': 1 }")
    Text findByKey(String key);

}

问题是在执行该查询时我得到了一个空值。获取一些数据的唯一方法是使它成为 return 一个 Project 实例,并且只对定义的字段进行 returned。但是没有办法让它编组到嵌套实体吗?

两点

问题是在执行该查询时我得到一个空值。 --> 当然你会得到空值,因为你的存储库是 TextsRepository,它将查找集合在无法找到的数据库中调用了 texts
您在数据库

中只有 projects 个集合
@Document(collection = "projects")  

您的查询是正确的,但您应该针对 ProjectRepository 执行此查询。

public interface ProjectRepository extends MongoRepository<Project, String> {

    @Query(value = "{'texts.key': ?0 }", fields = "{ 'texts.key' : 1, 'texts.defaultText': 1 }")
    Project findByKey(String key);   
}

查询方法的 return 类型应该可以分配给托管域类型(在您的项目中)。