我有一个聚合查询,该查询返回Operation
字段的范围amount:BigDecimal
大于minAmount
且在日期范围内的Operation
对象。operationId:String
基于,我只想得到不同的结果(每个对象都有一个)operationId
。
我在这里找到了一个相关示例,但它并不能帮助我解决问题:使用MongoTemplate获取排序的不同值
我了解addToSet
或group
可以使用,但尚不清楚如何在其余查询中准确地整合它
private List<OperationDataVO> getInfoFromDB(BigDecimal minAmount,
Instant startDate, Instant endDate) {
Criteria criterias = new Criteria()
.andOperator(Criteria.where(WinningOperation.AMOUNT)
.gte(minAmount)
.and(Operation.TYPE).is(OperationTypeEnum.WINNING_TYPE)
.and("createdAt").gte(startDate).lte(endDate));
MatchOperation matchOperation = Aggregation.match(criterias);
ProjectionOperation projectionOperation =
Aggregation.project("amount", "operationId");
Aggregation aggregation = Aggregation.newAggregation(matchOperation,
projectionOperation, sort(direction, "amount"));
AggregationResults<OperationDataVO> aggregate = mongoTemplate
.aggregate(aggregation, COLLECTION, OperationDataVO.class);
return aggregate.getMappedResults();
}
另外,我尝试在Aggregation
管道中添加组操作,但是这样做时,我得到了OperationDataVO
每个对象的两个字段都在哪里的列表null
(Aggregation aggregation = Aggregation.newAggregation(matchOperation, projectionOperation, sort(direction, "amount"), group("operationId"));
)
amount
在进行分组之前,您需要按降序排序。分组应使用“ $ first”累加器完成。我们使用保留整个文档$$ROOT
。然后,可以用组中的文档替换根文档。
分组不会保留任何顺序,因为您要对最终结果进行排序,因此需要再次排序。
实现此目的的mongo shell代码如下所示:
db.getCollection('operationData').aggregate([
{ $match: ... } ,
{ $project: { amount: 1, operationId: 1 } },
{ $sort: { amount: -1 } },
{ $group: { _id: '$operationId', g: { $first: {data: '$$ROOT'} }} },
{ $replaceRoot: { newRoot: '$g.data' }},
{ $sort: { amount: 1 } }
])
这将需要转换为Spring Data Mongo(也许我以后会花时间尝试一下)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句