Spring Mongodb 聚合不适用于 DBRef

问题描述

我有一个mongodbspring boot 中不起作用的聚合。如果有人能帮助我,我将不胜感激。 这是我的 ExplainDoc 课:

@Document(collection = "ExplainDoc")
public class ExplainDoc{

    @Id
    private String id;

    @TextIndexed(weight=3)
    private String product_in_brief;
    private Product product;
    
    @Textscore
    private Float textscore; }

这是我的另一堂课:

 @Document(collection = "product")
public class Product{   
    
    @Id 
    private String id;
    private String category;
}

我想要做的是进行文本搜索并找到所有在其 ExplainDoc 中包含给定文本的 product_in_brief,前提是他们的产品具有特定类别。 在我的搜索存储库中,我有如下聚合:

public List<MyAggrResults> searchBriefExplanations(String text,String category){
            
MatchOperation matchRegion = Aggregation.match(Criteria.where("product.category").is(category));
TextCriteria criteria = TextCriteria.forDefaultLanguage().matchingAny(text);
MatchOperation match = Aggregation.match(criteria);
GroupOperation group =   Aggregation.group("product.category").push("$$ROOT").as("myresults").sum("textscore").as("score");
Projectionoperation project = Aggregation.project("product_in_brief","product").andExpression("{$Meta: \"textscore\"}").as("textscore");
}

代码现在可以使用了。但是,我发现将 product 对象始终作为嵌套文档非常昂贵。如果我想将 product 对象用作 @DBRef,我应该如何更改代码?当我添加 @DBRef 时,代码不再起作用。我认为原因是 product.category 不再被识别。

希望有人能帮助我。

解决方法

DBRef 没有什么特别之处可以神奇地使其高效。它只是集合名称和 id 组合的标签。您仍然需要使用聚合管道来查询使用 DBRef 的数据,就像您不使用 DBRef 时查询的方式一样。