在聚合中将_id(ObjectId)转换为String以进行查找Spring Boot

时间:2020-09-27 06:56:49

标签: java mongodb spring-boot mongodb-query mongotemplate

这不是问题

很长时间以来,我在Spring Boot聚合中将objectId转换为字符串时遇到问题,但找不到任何有用的方法来解决它。 最后,我弄清楚了,我想和遇到同样问题的人分享我的方式。 如您所知,查找需要查找值相同的两个面,例如,两个面的objectId或两个面的字符串 如果在另一面有objecteId和string,则必须将此objectId设置为string,然后编写查找阶段; 查找之前的阶段应该是使用诸如下面的$ toString表达式的项目阶段:

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();

希望它会有用

0 个答案:

没有答案