Java 将聚合中的_id(ObjectId)转换为字符串以查找Spring引导
这不是问题 在SpringBootAggregation中将objectId转换为字符串的过程中,我遇到了一个很长时间的问题,我找不到任何有用的方法来解决它。 最后,我想和那些有同样问题的人分享我的方法; 正如您所知,查找需要查找相同值的两个边,例如,两个边objectId或两个边string 如果在另一侧有objectId和string,则必须将该objectId设置为string,然后编写查找阶段; 查找之前的阶段应该是使用$toString表达式的项目阶段,如下面所示:Java 将聚合中的_id(ObjectId)转换为字符串以查找Spring引导,java,mongodb,spring-boot,mongodb-query,mongotemplate,Java,Mongodb,Spring Boot,Mongodb Query,Mongotemplate,这不是问题 在SpringBootAggregation中将objectId转换为字符串的过程中,我遇到了一个很长时间的问题,我找不到任何有用的方法来解决它。 最后,我想和那些有同样问题的人分享我的方法; 正如您所知,查找需要查找相同值的两个边,例如,两个边objectId或两个边string 如果在另一侧有objectId和string,则必须将该objectId设置为string,然后编写查找阶段; 查找之前的阶段应该是使用$toString表达式的项目阶段,如下面所示: Projectio
ProjectionOperation projectionOperation = Aggregation.project(/*your nedded fields */)
.and(ConvertOperators.ToString.toString("$_id)).as("aggId");
然后您可以像下面这样轻松地使用查找:
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(
Criteria.where("cratorId").is(userId)
)
,
projectionOperation
,
Aggregation.lookup("post", "aggId", "courseId", "postList"),
我的全部汇总如下:
ProjectionOperation projectionOperation = Aggregation.project(/*your nedded fields */)
.and(ConvertOperators.ToString.toString("$_id")).as("aggId");
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(
Criteria.where("creatorId").is(userId)
)
,
projectionOperation
,
Aggregation.lookup("post", "aggId", "courseId", "postList")
);
return this.aggregate(agg, entityClass, Object.class).getMappedResults();
希望它能有用