I am trying to write a query on mongoDb to group the data by a particular field (storeId). Each group will have multiple records for same storeId. I need the records on each group to be ordered by a field (timeStamp). A yet better solution would be after sorting the records on each group, select the first record only so each group has only one record. This is what I tried:
const result = await deliverydays.aggregate([
{
$match: {
"storeId": { $in: storeIds },
"eci.openTimeStamp": { $ne: null },
"eci.dayStatus": "OPEN"
}
},
{
$group: {
_id: "$storeId",
data: {
$push: { openTimeStamp: "$eci.openTimeStamp", storeId: "$storeId" }
},
$sort: { openTimeStamp: 1 }
}
}
])
it is complaining with error "The field '$sort' must be an accumulator object" I tried this as well:
const result = await deliverydays.aggregate([
{
$match: {
storeId: { $in: storeIds },
"eci.openTimeStamp": { $ne: null },
"eci.dayStatus": "OPEN"
}
},
{
$group: {
_id: "$storeId",
data: {
$push: { openTimeStamp: "$eci.openTimeStamp", storeId: "$storeId" }
}
}
},
{
$sort: { openTimeStamp: 1 }
}
])
But still doesn't work. I realized that the second structure is only if I want to sort by "_id" or "data"
Any help would be appreciated. I apologize in advance if this is considered easy but I am new on the IT world and also I come from SQL server.
$sort: { "data.openTimeStamp": 1 }