我已经搜索了一段时间,找不到解决方案。也许我创建的查找错误,但这是我想要做的。
我有两个集合,其中一个引用另一个集合的ID,并存储为字符串。注意:在您问之前,我无法将“ parentId”转换为集合中的ObjectId。
汽车收藏:
{
id: ObjectId("1234")
... other car fields ...
},
{
id: ObjectId("2345")
... other car fields ...
}
评论集合
{
id: ObjectId("3456"),
commentMessage: "this is a comment",
parentRecordId: "1234"
},
{
id: ObjectId("4567"),
commentMessage: "this is another comment",
parentRecordId: "2345"
}
我正在将Spring Data MongoDB与MongoDB 3.6版一起使用。这是我的查询,我终生无法返回匹配的Car对象。
TextCriteria criteria = TextCriteria.forDefaultLanguage().matchingAny("comment");
MatchOperation match = Aggregation.match(criteria);
GroupOperation group = Aggregation.group("parentRecordId");
LookupOperation lookup = Aggregation.lookup("car", "_id", "_id", "car");
Aggregation aggregation = Aggregation.newAggregation(match, group, lookup);
AggregationResults<CommentAggregationResults> results = mongoTemplate.aggregate(aggregation, Comment.class, CommentAggregationResults.class);
这是模型对象CommentAggregationResults.class
public class CommentAggregationResults(){
@Id
private String id;
private Car car;
... getters and setters ...
}
我从该查询中期望的是来自数据库的两个响应。在我的CommentAggregationResults类中,我应该在“ id”字段中看到Car ID,在“ car”字段中看到Car对象本身。 (我将基于此查询来使其更有用,我只需要首先跳过此步骤即可。)
我在结果中看到的是两个CommentAggregationResults对象(与预期的一样)-ID设置正确。但是Car对象为空。
我的理论是,我需要以某种方式在此查询中将“ parentRecordId”字符串转换为ObjectId。
我该怎么做?还是有其他方法可以达到我想要的结果?