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.
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
}
}
])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.