我想创建一个使用spring数据mongodb的聚合查询
我的集合数据结构是:
{
date: ISODate("2022-12-11T01:13:00.000Z"),
metadata: {
homeId: '51b87ea3d846f450141ae58z',
nodeId: '51b87ea3d846f450141ae58z'
},
value: 42,
_id: ObjectId("63b583e30c1e523313b64ed5")
}
MongoDb查询,我想翻译到java是:
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}
}
]
)
MongoDb的查询结果如下所示:
[
{
_id: {
date: { year: 2022, month: 12, day: 11 }
},
cumulValue: 42
}
]
如你所见,结果结构是_id嵌套对象date包含年、月和日字段。
我想有相同的结果_id结构使用groupOperation与春季数据mongo。
我试过这个实现
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);
但是我不能有预期的结果结构(嵌套对象日期)
{
_id: {
year: 2022,
month: 11,
day: 11
},
cumulValue: 284
}
您可以通过解析整个管道字符串来尝试。
String groupStage = "{rn" +
" $group: {rn" +
" _id: {rn" +
" date: {rn" +
" year: "$date.year",rn" +
" month: "$date.month",rn" +
" day: "$date.day"rn" +
" }rn" +
" },rn" +
" cumulValue: {rn" +
" $sum: "$value"rn" +
" }rn" +
" }rn" +
" }"
GroupOperation groupOperation = context -> context.getMappedObject(Document.parse(groupStage));