我正在使用 Mongotemplate 使用 SpringBoot Mongodb。
我有一個包含以下示例檔案的包集合:
{
"_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"
并僅回傳以下欄位:
"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'
我究竟做錯了什么?
uj5u.com熱心網友回復:
在這種情況下您不需要replaceRoot,因為您要投影的欄位已經在根目錄下。此外,不需要$unwind和$group管道$match足以回傳給定查詢的匹配檔案。
相反,使用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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/432873.html
