How to I handle inserting/removing/sorting documents by a number attribute with the least number of resultant changes?

17 Views Asked by At

I have a collection of documents with a numeric property on the document called order. Inserting involves either appending a document to the end or inserting it somehwere in the middle. New documents are generally added at the end, and duplicated documents are generally inserted after/at their source's document. Removing a document can occur at any position. When fetching the documents, I use the database's built-in order-by functionality to sort the documents by the order property, as users expect to be able to re-order documents and have them appear as specified.

My problem is that any change to a single document's order through insertion, removal, or order update causes all the documents falling after the order of the newly changed document to be updated. This becomes an expensive operation (and sometimes buggy) when multiple documents are removed/updated at once or even when a single document is updated in a large collection.

Right now, cases of inserting/removing/reordering are handled manually to ensure that the order property on our documents always forms a zero-indexed sequential integer based list. Though the order property is never seen by users and isn't required by the fetching logic to be sequential, that's the most straightforward way to keep the logic bug free (as it stands).

I'm looking for an approach, either a generic algorithmic or a specific (Firebase/NoSQL Javascript) solution, that we can implement to help solve this problem with the least number of database writes/updates. While it seems like something I should've picked up in an algorithms class in college, nothing comes to mind or appears in google searches for this general problem.

0

There are 0 best solutions below