[英]Spring mongo aggregate get count and date by a date range
I want to get how many products sold in a specific date range.我想获得在特定日期范围内销售的产品数量。
final TypedAggregation<Product> otpTypedAggregation = newAggregation(Product.class,
match(Criteria.where(CREATED_AT).gte(fromDate).lte(toDate)),
project(CREATED_AT)
.andExpression("dayOfMonth(createdAt)").as("day")
.andExpression("month(createdAt)").as("month")
.andExpression("year(createdAt)").as("year"),
group(fields().and("day").and("month").and("year")).first("sold_at").as("sold_at")
.count().as("count"),
sort(new Sort(ASC, "sold_at"))
);
mongoTemplate.aggregate(otpTypedAggregation, Data.class).getMappedResults();
After the execution, I get an output like this执行后,我得到这样的输出
[Data(sold_at=Mon Jan 06 04:38:18 IST 2020, count=1), Data(sold_at=Mon Jan 06 10:23:03 IST 2020, count=1), Data(sold_at=Tue Jan 07 09:46:54 IST 2020, count=2)]
But this is how I wish to recieve the data:但这就是我希望接收数据的方式:
[Data(sold_at=Mon Jan 06 2020, count=2),Data(sold_at=Tue Jan 07 2020, count=2)]
So how to modify the code to get the above result?那么如何修改代码来得到上面的结果呢?
Provide sample data to check if it's valid solution.提供示例数据以检查它是否是有效的解决方案。
Note: If this is valid solution, I can translate into Spring-Data syntax.注意:如果这是有效的解决方案,我可以转换为 Spring-Data 语法。
db.product.aggregate([
{
$match: {}
},
{
$project: {
day: {
$dayOfMonth: "$createdAt"
},
month: {
$month: "$createdAt"
},
year: {
$year: "$createdAt"
}
}
},
{
$group: {
_id: {
day: "$day",
month: "$month",
year: "$year"
},
count: {
$sum: 1
}
}
},
{
$project: {
_id: 0,
sold_at: {
$dateFromParts: {
year: "$_id.year",
month: "$_id.month",
day: "$_id.day"
}
},
count: 1
}
},
{
$sort: {
sold_at: 1
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.