使用spring mongo模板,对嵌入式文档中的数组进行聚集的slice方法对我不起作用。
示例:
发票收据:
{
"reference_number": "aaa111",
"historical_data": {
"year": 2010,
"data": [
{
"item_name": "Apple",
"price": 50
},
{
"item_name": "Book",
"price": 200
}
]
}
}
使用mongoTemplate我只想获取切片中的历史数据。
对于直接在根目录下出现的需要切片的阵列,我找到了使用聚合的解决方案 请参阅:Spring mongo repository slice
对嵌入式文档中的数组应用类似的查询将返回一个空列表,即使有数据也是如此。
我正在尝试的查询是:
TypedAggregation<Invoice> agg = newAggregation(Invoice.class,
match(where("reference_number").is(referenceNumber)),
project.andExpression("historicalData.data").slice(limit, offset));
AggregationResults<Invoice> result = mongoTemplate.aggregate(agg, Invoice.class, Invoice.class);
但这会返回 空列表 。
Invoice.java
@Data
@Document(collection = "invoice")
public class Invoice {
@Id
private String id;
@NotEmpty
@Indexed(unique = true)
@Field("reference_number")
private String referenceNumber = UUID.randomUUID().toString();
@Valid
@Field("historical_data")
private HistoricalData historicalData = new HistoricalData();
}
历史数据:
@Data
public class HistoricalData {
@NotEmpty
@Field("year")
private Intger year;
@Valid
@NotNull
@Field("data")
private List<InvoiceData> data = new LinkedList<>();
}
注意: 我也尝试过:
TypedAggregation<Invoice> agg = newAggregation(Invoice.class,
match(where("reference_number").is(referenceNumber)),
project.andExpression("historical_data.data").slice(limit, offset));
AggregationResults<Invoice> result = mongoTemplate.aggregate(agg, Invoice.class, Invoice.class);
但这给了我一个PropertyPathException。
提前谢谢!
答案 0 :(得分:0)
经过数周的努力,我已经找到了解决方案:
ProjectionOperation project = project().and("historicalRevisionData.data").slice(limit, offset).as("historical_revision_data.data")
.andInclude("id")
.and("referenceNumber").as("reference_number");
TypedAggregation<Invoice> agg = newAggregation(Invoice.class,
match(where("reference_number").is(referenceNumber)),
project);
AggregationResults<TaxInvoice> aggregate = mongoTemplate.aggregate(agg, Invoice.class, Invoice.class);
希望这对其他人也有帮助。