MongoDB Aggregation - Does $unwind order documents the same way as the nested array order?

Hello @karaimin welcome to the community!

There is a chance that you get the same results but no guarantee. Personally I always use the sort after the unwind, ideal with an $match before the unwind to try to get as few documents as possible.

[
    {$match: { <query> } }
    {$unwind: "$values"}
    {$sort: {"_id": 1}},
]

The above will provide for sure the wanted result. However, I hope that one oft the MDB internals can elaborate on

  • the performance aspects - is there an option to prevent an in memory sort after the $unwind? Not sure if a wildcardIndex can help here.

Cheers,
Michael