I'm trying to group Orders array within the time interval and group them by date, sort them, and have all orders split into days. However, I'd like to sort the orders array on each day sorted within each day as well.
Orders.aggregate([{
$match: {
'created_at': {
$gte: timeInterval, //match last 3 days
}
}
}, {
"$group": {
_id: {
$dateToString: { format: "%d/%m/%Y", date: "$created_at", timezone: "Australia/Melbourne" } // group by date
},
orders: { $push: '$$ROOT' }
}
}, {
$sort: { '_id': -1 } // sort by date
}])
const OrderSchema = new Schema({
...,
created_at: {
type: Date,
default: Date.now
},
})
exData=[{_id: 26/12/2021, orders:[...]},{_id: 25/12/2021, orders:[...]}, ]
// need to sort orders array
I've tried:
{
$sort: { '_id': -1, "orders.created_at": -1 }
}
I would appreciate any help. Thanks.
CodePudding user response:
Your aggregation pipeline should be looked as below:
$match
- Filter documents by condition.$sort
- Sort documents bycreated_at
.$group
- Group bycreated_at
and addorders
for the accumulated field.
Orders.aggregate([
{
$match: {
'created_at': {
$gte: timeInterval, //match last 3 days
}
}
},
{
$sort: { "created_at": -1 }
},
{
$group: {
_id: {
$dateToString: { format: "%d/%m/%Y", date: "$created_at", timezone: "Australia/Melbourne" } // group by date
},
orders: { $push: '$$ROOT' }
}
}
])