groupProperty not work well
I use groupProperty in withCriteria, like this:
{
projections {
groupProperty("type")
property("type")
sum("isHUPDAT")//, "numOfHUPDAT")
sum("duration")//, "numOfDuration")
// countDistinct("logicalLogID") //"count"
}
}
Howerver the group not work well, I turn on the mongo profile to log execution, I found the mongo aggregation statement is
[ { $project: { type: 1, isHUPDAT: 1, duration: 1 } }, { $group: { _id: { type: "$type", _id: "$_id" }, sum_isHUPDAT: { $sum: "$isHUPDAT" }, sum_duration: { $sum: "$duration" } } } ]
Excatly, I just want to group by type, so correct group id should be like this { _id: { type: "$type" }.
So I trace the gorm mongo source code,
In grails-datastore-gorm-mongodb-6.1.6.RELEASE
org.grails.datastore.mapping.mongo.query.MongoQuery
there are codes as following:
projectProjectionHandlers.put(PropertyProjection.class, new ProjectionHandler() {
@Override
public String handle(PersistentEntity entity, Document projectObject, Document groupBy, PropertyProjection projection) {
String property = projection.getPropertyName();
projectObject.put(property, 1);
Document id = getIdObjectForGroupBy(groupBy);
String projectedValueKey = property.replace('.', '_');
id.put(projectedValueKey, "$" + property);
// we add the id to the grouping to make it not distinct
id.put(MongoEntityPersister.MONGO_ID_FIELD, "$" + MongoEntityPersister.MONGO_ID_FIELD);
return projectedValueKey;
}
});
You will alway and _id if I use group, which will make mistake.
// we add the id to the grouping to make it not distinct
id.put(MongoEntityPersister.MONGO_ID_FIELD, "$" + MongoEntityPersister.MONGO_ID_FIELD);
I don't know why? is it a bug or how can i do ?
If I remove
property('type')
It seems will not generate id.
[ { $project: { type: 1, isHUPDAT: 1, duration: 1 } }, { $group: { _id: { type: "$type", _id: "$_id" }, sum_isHUPDAT: { $sum: "$isHUPDAT" }, sum_duration: { $sum: "$duration" } } } ]
is groupProperty or perperty handler is wrong?
select sum(isHUPDAT), sum(duration) from xxx group by type. how do i write in criteria if I want so.