-
Type: Question
-
Resolution: Done
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: None
-
None
Many applications, e.g. todo lists, need to maintain a user-defined order of items. Suppose I have the following collections/documents:
users -> { _id, name }
todos -> { user_id, text, position }
I'd like to have todos look something like:
{ user_id: abc..., position: 0, text: "Do laundry" } { user_id: abc..., position: 1, text: "Clean room" } { user_id: abc..., position: 2, text: "Brush teeth" } { user_id: def..., position: 0, text: "Walk dog" } { user_id: def..., position: 1, text: "Buy dog toy" }For each user ID, the positions should always be 0, 1, 2... N with no duplicates and no gaps. Moreover, the users should be able to re-order their list, e.g. something like this UI, and maintain integrity of the list:
The problem is further explored here: https://begriffs.com/posts/2018-03-20-user-defined-order.html
I've implemented this in my Ruby application using the Mongoid Orderable gem: https://github.com/mongoid/mongoid_orderable. However, when processing many re-order actions with concurrent requests, my lists always get out of sync (position duplicates or gaps occur, e.g. positions become 0, 0, 1, 1, 1, 3, 4, 6, 6, 8... etc.)
I am experimenting using transactions with mixed results. I'd like to hear if there is a recommended/canonical way to do this in MongoDB?