【问题标题】:MongoDB order of elementsMongoDB 元素顺序
【发布时间】:2017-07-06 07:42:55
【问题描述】:

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

我使用 MongoDB 来保存所有数据。好的,所以现在我有了位置 4 的游戏。我想将其更改为位置 1。那么我需要做什么?

我需要将 MongoDB 中该游戏的字段位置从 4 更新为 1,并对该集合中位置 1 之后的所有文档进行增量。

但我认为这不是一个好主意!可能您有想法如何以更好的方式实施它?谢谢!

mongo 表示例:

_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

所以现在我在我的网站上按顺序显示游戏:泡泡 -> 泡泡A -> 泡泡B -> 泡泡C... 现在我想在我的网站游戏中按顺序显示:bu​​bbleC -> bubbleA -> bubbleB -> bubble... 所以要做到这一点,我需要将表中“bubbleC”的“位置”字段更新为“1”,并在名为“bubble”的文档之后为所有文档增加所有其他“位置”。但这是个坏主意。那么如何做得更好呢?

【问题讨论】:

  • 人们无法真正建议如何“移动数据”,除非您展示真实数据以及您正在尝试做什么。请编辑您的问题。
  • 更新了我的帖子,希望现在更清楚了)

标签: javascript node.js mongodb nosql


【解决方案1】:

如果您的文档数量相对较少并且不经常更改位置,那么您的方法还不错。

作为替代方案,您可以将位置元数据存储在单独的数组中。位置更新只会触及一个文档。基本 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

【讨论】:

    猜你喜欢
    • 2012-07-17
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 2011-02-07
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多