i want to grab data sorted by its date but the date is not in a field's value, its in the field's value's object's array(if i said it correctly).
here is an example of the data i have:
{
role: "User",
fullName: "Verna Pagac",
username: "dwightkoss95",
email: "[email protected]",
orders: [{
buyerUsername: 'admin',
boughtAt: 2022-09-20T20:14:59.304Z
},
{
buyerUsername: 'admin',
boughtAt: 2022-10-30T22:35:35.546Z
}]
}
after i extracted the orders by the following command, i want to sort them by the boughtAt but how?
const usersWithOrders = await users
.find({
orders: { $exists: true, $ne: [] }
})
const orders = []
usersWithOrders.map((user) => {
for (i=0 ; i<user.orders.length ; i ) {
orders.push(user.orders[i])
}
})
i want the newer order to be top.
console.log(orders)
// now it shows the following out put:
/*
[{
buyerUsername: 'admin',
boughtAt: 2022-09-20T20:14:59.304Z
},
{
buyerUsername: 'admin',
boughtAt: 2022-10-30T22:35:35.546Z
}]
*/
CodePudding user response:
If you want you can sort directly from db using the aggregation framework
db.users.aggregate([
{ $unwind: '$orders' },
{ $sort: { 'orders.boughtAt': -1 } },
{
$group: {
_id: '$_id',
user: { $first: '$$ROOT' },
orders: { $push: '$orders' },
},
},
])
or if you prefer you can sort in JS
orders.sort((a, b) => b.boughtAt - a.boughtAt)