[英]Aggregation query with Spring Data mongoDb using group opertation with Nested field
I want to create an aggregation Query using spring data mongodb.我想使用 spring 数据 mongodb 创建聚合查询。
My collection data structure is:我的收藏数据结构是:
{
date: ISODate("2022-12-11T01:13:00.000Z"),
metadata: {
homeId: '51b87ea3d846f450141ae58z',
nodeId: '51b87ea3d846f450141ae58z'
},
value: 42,
_id: ObjectId("63b583e30c1e523313b64ed5")
}
The MongoDb Query that I want to translate to java is:我要转换为 java 的 MongoDb 查询是:
db.consumptions.aggregate(
[
{ $match : {"metadata.nodeId": "51b87ea3d846f450141ae58z"}
},
{ $project: {
date: {
$dateToParts: { date: "$date"}
},
value: 1
}
},
{ $group: {
_id: {
date: {
year: "$date.year", month: "$date.month", day: "$date.day"
}
},
cumulValue: { $sum: "$value"}
}
},
{ $sort : { "_id.date": -1}
}
]
)
The MongoDb Query result looks like this: MongoDb 查询结果如下所示:
[
{
_id: {
date: { year: 2022, month: 12, day: 11 }
},
cumulValue: 42
}
]
So as you can see here, the result structure is _id with a nested object date containing fields year, month and day.因此,正如您在此处看到的,结果结构是_id ,嵌套的 object日期包含字段年、月和日。
I would like to have the same result _id structure using groupOperation with spring data mongo.我想使用 groupOperation 和 spring 数据 mongo 获得相同的结果 _id 结构。
I tried this implementation我试过这个实现
MatchOperation matchOperation = Aggregation.match(
new Criteria().andOperator(Criteria.where("metadata.nodeId").is(nodeId);
// projection Operation
ProjectionOperation projectionOperation = project("value")
.and(DateOperators.dateOf("date").toParts()).as("date");
// group Operation
GroupOperation groupOperation = Aggregation.group(
"date.year", "date.month", "date.day")
.sum("value").as("cumulativeValue");
// Sort Operation
SortOperation sortOperation = sort(pageRequest.getSort());
Aggregation aggregation = Aggregation.newAggregation(
matchOperation, projectionOperation, groupOperation,sortOperation);
But I'm not able to have the expected result structure (with nested object date)但我无法获得预期的结果结构(嵌套日期为 object)
{
_id: {
year: 2022,
month: 11,
day: 11
},
cumulValue: 284
}
You can try this by parsing the entire pipeline string.您可以通过解析整个管道字符串来尝试此操作。
String groupStage = "{\r\n" +
" $group: {\r\n" +
" _id: {\r\n" +
" date: {\r\n" +
" year: \"$date.year\",\r\n" +
" month: \"$date.month\",\r\n" +
" day: \"$date.day\"\r\n" +
" }\r\n" +
" },\r\n" +
" cumulValue: {\r\n" +
" $sum: \"$value\"\r\n" +
" }\r\n" +
" }\r\n" +
" }"
GroupOperation groupOperation = context -> context.getMappedObject(Document.parse(groupStage));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.