How to store an ordered set of documents in MongoDB without using a capped collection

前端 未结 4 1623
囚心锁ツ
囚心锁ツ 2020-12-28 23:11

What\'s a good way to store a set of documents in MongoDB where order is important? I need to easily insert documents at an arbitrary position and possibly reorder them lat

4条回答
  •  暖寄归人
    2020-12-28 23:26

    Here is a link to some general sorting database answers that may be relevant:

    https://softwareengineering.stackexchange.com/questions/195308/storing-a-re-orderable-list-in-a-database/369754

    I suggest going with Floating point solution - adding a position column:

    Use a floating-point number for the position column. You can then reorder the list changing only the position column in the "moved" row. If your user wants to position "red" after "blue" but before "yellow" Then you just need to calculate

    red.position = ((yellow.position - blue.position) / 2) + blue.position

    After a few million re-positions you may get floating-point numbers so small that there is no "between" -- but this is about as likely as sighting a unicorn.

    When retrieving it you can simply say col.sort() to get it sorted and no need for any client-side code (Like in the case of a Linked list solution)

提交回复
热议问题