I\'m having a problem applying a sort to an aggregation grouping. My raw data looks like the following:
{
\"_id\" : ObjectId(\"52deab2fe4b0a491
so here is the issue come sorting over the Aggregation result.
Here the field which you are sorting is the part of the ID, so basically your aggregation operation is performing the average operation and returning the result sets with 2 Fileds called "_id" and "buildDuration" , since you are doing sorting over the inner field of "_id", you have to define Sort attributes in following Way.
{ $sort: {
'_id.buildProjectName': 1,
'_id.year': 1,
'_id.month': 1,
'_id.day': 1
} }
Hopefully, this will help you. Contact me if you have any doubt.
The fields you're sorting on are part of the _id
so you need to include that in your $sort
field names:
db.builds.aggregate([
{ $group: {
_id: {
month: { $month: "$time" },
day: { $dayOfYear: "$time" },
year: { $year: "$time" },
buildProjectName: "$data.buildProjectName",
},
buildDuration: { $avg: "$data.buildDuration" }
} },
{ $sort: {
'_id.buildProjectName': 1,
'_id.year': 1,
'_id.month': 1,
'_id.day': 1
} }
])