【问题标题】:How to dynamically construct MongoDB Criteria object for Aggregation.match?如何为 Aggregation.match 动态构造 MongoDB Criteria 对象?
【发布时间】:2023-01-21 02:36:28
【问题描述】:
我有以下 JSON 对象,我想将其转换为 Criteria 对象,以便我可以在 Aggregation.match() 查询中使用。
{
"_filter": {
"$and": [
{
"$or": [
{
"country": "India"
},
{
"age": 20
}
]
}
]
},
"_page": {
"pageNum": 0,
"recordsPerPage": 1
}
}
我已经看到我们有 BasicQuery 对象,它可以从 _filter 字段的内容构造。但是,我无法从中推断出 Criteria 对象。
Spring Data MongoDB 中是否有任何方法/实用程序可以执行此操作?
【问题讨论】:
标签:
java
spring-data-mongodb
【解决方案1】:
实际上,Criteria 是一个包装类,用于将您从 MongoDB 语法中抽象出来,并以一种优雅的方式构建查询。
我想转换为 Criteria 对象,以便我可以在 Aggregation.match() 查询中使用
没有必要这样做。尝试这个:
AggregationOperation match = ctx => new Document("$match", Document.parse(your_json).get("_filter"));
...
Aggregation agg = Aggregation.newAggregation(match)
.withOptions(Aggregation.newAggregationOptions().allowDiskUse(Boolean.TRUE).build());
mongotemplate.aggregate();
mongoTemplate.aggregate(agg, inputType, outputType).getMappedResults();