Hi,
I´m trying to do an aggregation in Java (spring boot) with mongoTemplate.
The problem is that when I try to group and sort by attribute in composite _id
the query makes the library wrong.
I do like this:
group:
- fields is an array of fields I´m trying to group.
Aggregation.group(fields).sum("count").as("count");
Sort:
Aggregation.sort(Sort.Direction.DESC,"_id.operationDate")
.and(Sort.Direction.DESC,"count");
aggregation = newAggregation(
match(matchCriteria),
group,
sort,
skip(elementsToSkip),
limit(pageable.getPageSize()));
AggregationResults<DocumentOut> list = mongoTemplate.aggregate(aggregation,
"nameCollection", DocumentOut.class);
But the result query is like this:
db.getCollection('jouJournalKPIsByDay').aggregate([
{ "$match" : { "_id.operationDate" : {
$lt: ISODate("2023-05-21T00:00:00.000+00:00"),
$gte: ISODate("2020-10-01T00:00:00.000+00:00")},
"_id.instanceCode" : "ESR1"}},
{ "$group" : { "_id" : { "instanceCode" : "$_id.instanceCode", "operationDate" : "$_id.operationDate"}, "count" : { "$sum" : "$count"}}},
{ "$sort" : { "_id._id.operationDate" : -1, "count" : -1}}, { "$skip" : 0}, { "$limit" : 55}
])
As you can see in the sort operation query print "_id._id.operationDate"
but on the other side in group print "_id.operationDate"
The class is like that:
@Document(collection = "nameCollection")
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class DocumentOut{
@JsonProperty("_id")
@Id
private IdKPIsByDay id;
/** Counter. */
private Double count;
}
and ID Class is like this:
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ToString
public class IdKPIsByDay implements Serializable {
/** Operation Date. **/
private LocalDate operationDate;
/** Instance code. */
private String instanceCode;
}
I don´t know what is the problem if someone can help me. I don´t know if it is a bug in the library.
When I don´t use group operation, the library prints well, print:
{ "$sort" : { "**_id.operationDate**" : -1, "count" : -1}}, { "$skip" : 0}, { "$limit" : 55} instead of { "$sort" : { "**_id._id.operationDate**" : -1, "count" : -1}}, { "$skip" : 0}, { "$limit" : 55}
I´ll try a lot of things but nothing works.
If I put sort operation first then the group operation library prints sort ok "_id.operationDate"
, but after sort, I think do group operation, and the result is not sorted.
Thanks.