I’m attempting to group sessions by location, and then sort the session objects within the nested Sessions array by StartTime. I’ve found a way to do this using an index on StartTime, which is used in the initial $match, but I’d like a way to explicitly specify my sorting intentions. Does anyone have a way I can do this?
This how I would like the aggregation to work. Essentially the $sort stage here does nothing. Is there any way to $sort the objects pushed into Sessions in the $group stage by StartTime?
db.getCollection('sessions').aggregate([
{
$match: {
$and: [
{ "StartTime": { $gte: ISODate("2020-02-01T18:52:34.000Z") } },
{ "StartTime": { $lte: ISODate("2020-02-02T18:52:34.000Z") } }
]
}
},
{
$group: {
_id: { id: "$locationId" },
numberOfSessions: { $sum: 1 },
Sessions: {
$push: {
_id: "$_id",
SessionID: "$SessionID",
StartTime: "$StartTime",
EndTime: "$EndTime"
}
}
}
},
{
$match: {
numberOfSessions: { $gte: 2 }
}
},
{ $sort: { 'Sessions.StartTime': 1 } },
{ $project: { StartTime: -1, Sessions: -1, numberOfSessions: -1 } }
],
{
allowDiskUse: true
}
)