[英]Nested class object with Spring data MongoDb aggregation returns null field
我在聚合中包含嵌套的 class 时遇到问题。
这是我收藏中 json 文档的预览:
{
"id": "1234",
"typeApp": "API",
"name": "name",
"versionNum": "1",
"release": {
"author": "name",
//some other data
}
}
文档 java class:
@Document(collection = "myClassExamples")
public class MyClassExampleDocument {
@Id
private String id;
private String typeApp;
private String name;
private String versionNum;
private Release release;
public static class Release {
private String author;
//Other fields...
}
}
我正在尝试构建一个查询,通过参数中的给定typeApp查找最后一个文档组,并按versionNum DESC排序以通过typeApp获取新文档。
我从一个更简单的查询开始,一个简单的typeApp组:
Aggregation aggregation = newAggregation(
Aggregation.sort(Sort.Direction.DESC, "versionNum"),
Aggregation.group("typeApp"),
project(MyClassExampleDocument.class)
)
该查询返回MyClassExampleDocument列表,其中所有字段都具有 null 值,但使用typeApp填充的id除外。
您知道如何构建聚合以获取存储在我的集合中的整个 object 吗?
谢谢您的帮助 !
您可以使用如下
public List<MyClassExampleDocument> test() {
Aggregation aggregation = Aggregation.newAggregation(
sort(Sort.Direction.DESC, "versionNum"),
group("typeApp").first("$$ROOT").as("data")
replaceRoot("data")
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(MyClassExampleDocument.class), MyClassExampleDocument.class).getMappedResults();
}
这是聚合
db.collection.aggregate([
{ "$sort": { versionNum: -1 } },
{
"$group": {
"_id": "$typeApp",
"data": { "$first": "$$ROOT" }
}
},
{ "$replaceRoot": { "newRoot": "$data" } }
])
工作Mongo游乐场
注意:java 代码未经测试,它是基于工作 mongo 脚本实现的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.