在聚合中将 _id(ObjectId) 转换为 String 以便查找 Spring boot

问题描述 投票:0回答:3

这不是问题

我在 Spring Boot 聚合中将 objectId 转换为字符串时遇到了很长时间的问题,但我找不到任何有用的方法来解决它。 最后,我想通了,我愿意将我的方法分享给那些有同样问题的人; 如您所知,查找需要查找两侧具有相同的值,例如两侧 objectId 或两侧字符串 如果您在另一侧有 objecteId 和字符串,则必须将此 objectId 转换为字符串,然后编写查找阶段; 查找之前的阶段应该是使用 $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();

希望它有用

java mongodb spring-boot mongodb-query mongotemplate
3个回答
1
投票

我也在研究这个问题的答案,我找到了这个解决方案。

我正在使用

spring-data-mongodb:3.0.0.RELESE

在您的聚合管道中

AddFieldsOperation.builder().addField("strId")
                    .withValue(
                        ConvertOperators.ToString.toString("$_id")
                    ).build()

这相当于

{
    $addFields: {
        strId: {$toString: "$_id"}
    }
}

您可以将

strId
替换为您想要的任何名称,并在下一步操作中使用它。


1
投票
List<Map> getMultiTable(){
    ProjectionOperation projectionOperation = Aggregation.project(/*your nedded fields */)
            .and(ConvertOperators.ToString.toString("$_id")).as("_id")
            .and(ConvertOperators.ToObjectId.toObjectId("$userId")).as("userId");

    Aggregation agg = Aggregation.newAggregation(
            Aggregation.match(
                    Criteria.where("status").is(0)
            ),
            projectionOperation,
            Aggregation.lookup("videoComment", "_id", "videoId", "commentList"),
            Aggregation.lookup("user", "userId", "_id", "userList")
    );

    List<Map> result = mongoTemplate.aggregate(agg, "mediaFile", Map.class).getMappedResults();
    System.out.println(result);
    return result;
}

0
投票

{ $查找:{ 来自:“团体成员”, 让:{cID:“$cID”}, 管道:[ { $匹配:{ $表达式:{ $和:[ { $eq: ["$groupId", "$$cID"] }, { $eq: ["$status", "ACTIVE"] }, // { $eq: ["$member.userId", "[电子邮件受保护]"] }, { $eq: ["$organizationId", 260] } ] } } },

想要等效的代码

© www.soinside.com 2019 - 2024. All rights reserved.