Mongodb 如何在Spring Mongo数据聚合中使用DateOperators
我们在Spring Data Mongo中设置了聚合管道,如下所示:Mongodb 如何在Spring Mongo数据聚合中使用DateOperators,mongodb,aggregation-framework,spring-data-mongodb,Mongodb,Aggregation Framework,Spring Data Mongodb,我们在Spring Data Mongo中设置了聚合管道,如下所示: MatchOperation matchStage = ... Fields groupingFields = Fields.fields(); groupingFields.and(name1, target1); groupingFields.and(name2, target2); ... GroupOperation groupStage = Aggregation.group(groupingFields); Lis
MatchOperation matchStage = ...
Fields groupingFields = Fields.fields();
groupingFields.and(name1, target1);
groupingFields.and(name2, target2);
...
GroupOperation groupStage = Aggregation.group(groupingFields);
List<AggregationOperation> aggStages = new ArrayList<>();
aggStages.add(matchStage);
aggStages.add(groupStage);
Aggregation aggregation = Aggregation.newAggregation(aggStages);
我的问题是,如何在Spring管道中使用$dayOfYear操作符。Spring支持DateOperators.DayOfWeek等DateOperators,但我无法将其合并到管道中。如何修改groupStage,以便根据需要按各种与日期相关的部分进行分组?对于某些操作,我通常遵循Bson文档样式
@Autowired
private MongoTemplate mongoTemplate;
public List<Object> test() {
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("state").is("XY"))
p-> new Document("$group",
new Document("_id",
new Document("city","$city")
.append("dayOfYear",
new Document("$dayOfYear", "$date")
)
).append("totalProfit",
new Document("$sum","$$profit")
)
)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}
@Autowired
私有MongoTemplate MongoTemplate;
公共列表测试(){
聚合=聚合。新聚合(
匹配(标准。其中(“状态”)为(“XY”))
p->新文档(“$group”,
新文档(“\u id”,
新文件(“城市”和“$city”)
.append(“dayOfYear”,
新文件($dayOfYear,“$date”)
)
).append(“总利润”,
新文件(“$sum”和“$$PROFICT”)
)
)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE.build());
返回mongoTemplate.aggregate(聚合,mongoTemplate.getCollectionName(您的_COLLECTION.class),Object.class).getMappedResults();
}
如果您发布的上述聚合正在工作,那么这应该是可行的。你可以参考。
我还没有试过
DateOperator
。但我很好奇它是怎么工作的。如果我知道了,我会更新的。在此之前,您没有拦截器谢谢,我正在寻找一种方法,可以保留或修改当前的分组操作,以适应按日期相关字段进行的额外分组。管道有点复杂,它有条件地在不同的地方添加分组字段,最后使用这些字段构建一个分组阶段,我希望避免转换为Bson样式。是的,你是对的。Bson格式有点复杂,但你不能总是避免它。例如,spring数据不支持子相关查找。所以你需要使用这种bson格式化程序。我也尽量避免。祝你好运,如果你发现Spring数据API定义了复杂的分组条件,请更新我
@Autowired
private MongoTemplate mongoTemplate;
public List<Object> test() {
Aggregation aggregation = Aggregation.newAggregation(
match(Criteria.where("state").is("XY"))
p-> new Document("$group",
new Document("_id",
new Document("city","$city")
.append("dayOfYear",
new Document("$dayOfYear", "$date")
)
).append("totalProfit",
new Document("$sum","$$profit")
)
)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}