MongoDB元素的顺序

我的应用程序有一个游戏列表。 每个游戏都有一个位置(向用户显示的顺序是:1,2,3 …)。

我正在使用MongoDB来保存所有的数据。 好的,所以现在我有了位置4的游戏。 我想把它改成位置1.那么我需要做什么?

我需要在MongoDB中将这个游戏的场地位置从4更新为1,并且对位于1之后的这个集合中的所有文档进行增量。

但是我觉得这不是个好主意! 可能你有想法如何更好地实施它? 谢谢!

蒙戈表的例子:

_id | name | description | position | ________________________________________________________ ObjectId("...") | bubble | some description | 1 ObjectId("...") | bubbleA | some description | 2 ObjectId("...") | bubbleB | some description | 3 ObjectId("...") | bubbleC | some description | 4 ObjectId("...") | bubbleD | some description | 5 ObjectId("...") | bubbleE | some description | 6 ObjectId("...") | bubbleF | some description | 7 

所以现在在我的网站上我按顺序展示游戏:泡泡 – > bubbleA – > bubbleB – > bubbleC …现在我想在我的网站游戏中按顺序展示:bubbleC – > bubbleA – > bubbleB – > bubble。所以要做到这一点,我需要更新我的表中的“位置”字段为“bubbleC”为“1”,并增加所有文件后名称为“泡沫”的所有文件的所有其他“职位”。 但这是一个坏主意。 那么如何做得更好呢?

如果您的文件数量相对较less,而且您的位置也不会太多,那么您的方法并不是那么糟糕。

作为替代,您可以将位置元数据存储在单独的数组中。 头寸更新只会触及一个文件。 基本的Python例子:

 def move(positions, old_index, new_index): element = positions.pop(old_index) positions.insert(new_index, element) return positions # Fetch array from MongoDB (or from anywhere really) positions = [ { '_id': 'ObjectId("...")', 'name': "bubble", 'description': "some description" }, { '_id': 'ObjectId("...")', 'name': "bubbleA", 'description': "some description" }, { '_id': 'ObjectId("...")', 'name': "bubbleB", 'description': "some description" }, { '_id': 'ObjectId("...")', 'name': "bubbleC", 'description': "some description" }, { '_id': 'ObjectId("...")', 'name': "bubbleD", 'description': "some description" }, { '_id': 'ObjectId("...")', 'name': "bubbleE", 'description': "some description" }, { '_id': 'ObjectId("...")', 'name': "bubbleF", 'description': "some description" } ] old_index = 3 new_index = 0 move(positions, old_index, new_index) # New positions: # # [{'_id': 'ObjectId("...")', 'description': 'some description', 'name': 'bubbleC'}, <-- # {'_id': 'ObjectId("...")', 'description': 'some description', 'name': 'bubble'}, # {'_id': 'ObjectId("...")', 'description': 'some description', 'name': 'bubbleA'}, # {'_id': 'ObjectId("...")', 'description': 'some description', 'name': 'bubbleB'}, # {'_id': 'ObjectId("...")', 'description': 'some description', 'name': 'bubbleD'}, # {'_id': 'ObjectId("...")', 'description': 'some description', 'name': 'bubbleE'}, # {'_id': 'ObjectId("...")', 'description': 'some description', 'name': 'bubbleF'}] 

编写一个小的帮助函数将有助于通过_idname移动元素。