Reorder an array of objects

Hello guys!

I am stuck here trying to find the best approach to reorder an array of objects.
imagine having an array Agenda that holds multiple AgendaItem objects and the user is free to reorder this array by dragging and dropping any agendaItem to any position.

Here is a sample of what is this array looks like and what I want to do with it.


so simply if array is like : [ startup, warming, running, celebrating ]
and user moved celebrating to the second position
it will be like: [ startup, celebrating, warming, running ] - (not just swapping)

what I thought of is deleting the second object and inserting it back at its target position using $position
and by that all other elements would be shifted to their new positions.
but I think this approach is not completely safe as if the app crashes between these 2 updates I will lose this item.

another approach is to $set the entire agenda with every reorder-request but this too doesn’t seem to be right to have a large object sent multiple times.
I also don’t have the sense yet to judge if this object is actually large or with normal size so I discarded this approach.
(I also cannot have the array cached and send it every few seconds as the business needs it to have it, more like, real-time across multiple clients)

I also thought of adding a new attribute as index to every object and send an array with their new indices after reording and have mongodb handle this sorting by their new indices but I cannot find a method that does so in mongodb.

so what would you usually do in this scenario?
Thank you! :slight_smile:

Hello @Hamza_Muhammad

Add one more field position and update whenever the position changes and sort it by the position value.

Just check if that works.


I would then have to update the entire list’s position values first then sort it by the position values.