substr is not working… is there any problem?
Hi,
You can see from the second result of the aggregation count (i.e. 6633) that it’s the total number of the first aggregation result i.e. (5400 + 1233). The numbers are totalled (grouped) because they shared the same group id. As you may be aware, this is because string substr(regDate, 0, 7) is not being evaluated but treated as a string value for group id . See also $group operator.
One way to achieve what you’re after with spring-data MongoTemplate is to use ProjectOperation first, for example:
AggregationResults<Document> cur = mongoTemplate.aggregate(newAggregation(
project()
.andExpression("substr(date, 0, 7)")
.as("regDate"),
group("regDate").count().as("count"),
sort(Sort.Direction.DESC, "regDate")),
"collectionName",
Document.class);
The above snippet is tested using spring-data-mongodb v1.10.1, MongoDB Java Driver v3.4.2 and MongoDB Server v3.4.x.
If you have further questions, please provide:
Regards,
Wan.