Il problema è che molte risposte online non ricostruiscono l’array dopo l’ordinamento. Puoi farlo con $group e $push, usando $first per mantenere gli altri campi:
db.TrafficStatistic.aggregate([
{ $unwind: "$statistic" },
{ $sort: { "_id": 1, "statistic.data.desktop.users": 1 } },
{ $group: {
_id: "$_id",
monthStart: { $first: "$monthStart" },
monthEnd: { $first: "$monthEnd" },
date: { $first: "$date" },
statistic: { $push: "$statistic" }
}}
])Ordinare anche per "_id" mantiene ordinato l’array di ciascun documento, essenziale quando $group ricostruisce tutto.