Sorting inner array of objects in find vs keeping array sorted in write operations

Hello all, i want to make a question regarding performance between two approaches.
I have an array of nested objects inside collection.
The schema of each object inside the array is the following:

{
 startDate: ISODate,
 endDate: ISODate
}

Is it better to keep this array of objects sorted thus sorting the array in every write operation or is it better to sort the array with aggregation when retrieving the document with the array, like this:

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

What would be the best in terms of performance?

What happens more often? Writing to the array or reading it? If it’s 99% reading, then keep them in order, if it’s 99% writing often then perhaps just sort as needed…
A write it going to overwrite the document anyway if you push a new entry so perhaps not so much more of an overhead to push it sorted, you’ll find a number of solutions on the forums for inserting in the correct place into an array.

You can always try it out, create a few million records and add a new item to them sorted and un-sorted to compare performance and IO overhead.

1 Like