MongoTemplate 聚合 replaceRoot 不起作用

MongoTemplate aggregation replaceRoot not working

我正在使用 SpringBoot + Mongodb 使用 Mongotemplate。

我有一个 packs 集合,其中包含以下示例文档:

{
    "_id" : ObjectId("61de8228a992b10804b3f1ae"),
    "pack_uuid" : "f67cb514-326c-4933-8e23-0580c912896c",
    "pack_name" : "covid 19",
    "pack_description" : "covid is dengeours",
    "created_by" : "ea41c6b8-aaec-4d9b-a5a7-a6a72ca4c9f6",
    "members" : [{
        "_id" : "0aa4b098-aab3-4ccf-8401-d52e6a4e42cc",
        "user_uuid" : "1f9b5f0b-f9f6-45d7-b25b-a5319307569f",
        "joining_date" : ISODate("2022-01-12T16:24:34.719Z")
    },{
        "_id" : "0aa4b098-aab3-4ccf-8401-d52e6a4e42cc",
        "user_uuid" : "2f9b5f0b-f9f6-45d7-b25b-a5319307569f",
        "joining_date" : ISODate("2022-01-12T16:24:34.719Z")
    }]
}

我需要实现 where 条件来检查传递的用户是否是 pack 的成员。类似于:

"members.user_uuid": "1f9b5f0b-f9f6-45d7-b25b-a5319307569f"

和 return 仅以下字段:

"pack_uuid" : "f67cb514-326c-4933-8e23-0580c912896c",
"pack_name" : "covid 19",
"pack_description" : "covid is dengeours",
"created_by" : "ea41c6b8-aaec-4d9b-a5a7-a6a72ca4c9f6",

我尝试了以下代码:

AggregationOperation match = Aggregation.match(
    Criteria.where("members.user_uuid").is(userUUID)
);
AggregationOperation unwind = Aggregation.unwind("members");
AggregationOperation group = Aggregation.group("_id");
AggregationOperation replaceRoot = Aggregation.replaceRoot(Aggregation.ROOT);

List<AggregationOperation> operations = new ArrayList<>();
operations.add(unwind);
operations.add(match);
operations.add(group);
operations.add(replaceRoot);

Aggregation aggregation = Aggregation.newAggregation(operations);

List<Pack> packs = mongoTemplate.aggregate(aggregation, Pack.class, Pack.class).getMappedResults();

我收到这个错误:

Invalid reference '$$ROOT'

我做错了什么?

在这种情况下您不需要 replaceRoot,因为您要投影的字段已经在根目录中。此外,不需要 $unwind$group 管道,因为 $match 足以 return 匹配给定查询的文档。

相反,使用 ProjectionOperation 排除成员字段,如下所示:

AggregationOperation match = Aggregation.match(
    Criteria.where("members.user_uuid").is(userUUID)
);
ProjectionOperation project = Aggregation.project().andExclude("members");

List<AggregationOperation> operations = new ArrayList<>();
operations.add(match);
operations.add(project);

Aggregation aggregation = Aggregation.newAggregation(operations);

List<Pack> packs = mongoTemplate.aggregate(aggregation, Pack.class, Pack.class).getMappedResults();