将Mongo Json命令转换为Spring查询对象
有人能告诉我这个mongodb shell命令的正确Spring聚合对象是什么吗将Mongo Json命令转换为Spring查询对象,spring,mongodb,mongodb-query,spring-data,aggregation-framework,Spring,Mongodb,Mongodb Query,Spring Data,Aggregation Framework,有人能告诉我这个mongodb shell命令的正确Spring聚合对象是什么吗 {$sort: {labelId:1, dataId:1, updatedAt:1}}, {$group: { "_id": { "lid" : "$labelId", "dataId":"$dataId" }, "dat": { $last:"$updatedAt"
{$sort: {labelId:1, dataId:1, updatedAt:1}},
{$group:
{
"_id":
{
"lid" : "$labelId",
"dataId":"$dataId"
},
"dat":
{
$last:"$updatedAt"
},
"value":
{
$last:"$value"
}
}
}
您可以使用spring mongo编写它,如下所示:
Aggregation aggregation = newAggregation(
sort(Direction.ASC,"labelId")
.and(Direction.ASC,"dataId")
.and(Direction.ASC,"updatedAt"),
group(Fields.fields().and("labelId","lid").and("dataId"))
.last("updatedAt").as("dat")
.last("value").as("value")
);
作为一个小提示,我喜欢在运行之前有一些东西来倾倒管道:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
// debug pipeline
System.out.println(
gson.toJson(
gson.fromJson(aggregation.toDbObject("spring", Aggregation.DEFAULT_CONTEXT).toString(), Object.class)
)
);
这给了我一个很好的序列化输出来检查:
{
"aggregate": "spring",
"pipeline": [
{
"$sort": {
"labelId": 1.0,
"dataId": 1.0,
"updatedAt": 1.0
}
},
{
"$group": {
"_id": {
"labelId": "$lid",
"dataId": "$dataId"
},
"dat": {
"$last": "$updatedAt"
},
"value": {
"$last": "$value"
}
}
}
]
}
谢谢你的回答。当我发现结果与我查询的集合不同时,如何执行此聚合?@skylla这对于聚合输出是常见的。通常最好像在mongoOperation.AggregateAgregation、spring、DBObject.class中一样使用DBObject.class。或者,将一个类定义为预期的输出形状,并使用该类对输出进行类型化聚合。