在Mongodb中将数据存储为对象与数组

时间:2020-07-29 10:05:45

标签: mongodb mongodb-compass

我想知道在mongoDB中存储大量唯一数据时哪种更好的做法。 在我的收藏集中,每个文档都有一个名为shapes的键,它包含一系列形状(最多可能有数千个),每个形状都有自己的属性,如下所示:

[
  {
    _id: ...,
    title: 'design one',
    shapes: {
       shapeid-123126: {
         id: 'shapeid-123816',
         fill: 'red',
         type: 'square'
       },
       shapeid-928372: {
         id: 'shapeid-928372',
         fill: 'red',
         type: 'square'
       }
    }
  },
  {
    _id: ...,
    title: 'design two',
    shapes: {
       shapeid-52316: {
         id: 'shapeid-52316',
         fill: 'red',
         type: 'square'
       },
       shapeid-634372: {
         id: 'shapeid-634372',
         fill: 'red',
         type: 'square'
       }
    }
  }
]

我的问题是:当唯一形状的数量可能成千上万时,将数据简单地存储在数组中是否是更好的做法?

[
  {
    _id: ...,
    title: 'design one',
    shapes: [
       {
         id: 'shapeid-123816',
         fill: 'red',
         type: 'square'
       },
       {
         id: 'shapeid-928372',
         fill: 'red',
         type: 'square'
       },
       // ... etc up to 1000's
    ]
  },
  {
    _id: ...,
    title: 'design two',
    shapes: [
       {
         id: 'shapeid-52316',
         fill: 'red',
         type: 'square'
       },
       {
         id: 'shapeid-634372',
         fill: 'red',
         type: 'square'
       },
       // ... etc up to 1000's
    ]
  }
]

我目前以第一种方式设置数据库的原因是因为使用键访问来更新数据客户端比必须先查找索引然后更新要快得多,所以我只是将数据结构传递给数据库。我只是不确定这是否明智。

我已经遇到了第一个难题,尝试从Compass导出数据意味着必须选择所有键({{1},_idtitleshapes ,,shapes.shapeid-123126shapes.shapeid-123126.fill,...等),因为shapes.shapeid-123126.type是对象,而不是数组,这意味着必须选择每种形状的所有属性作为模式。

我导出了这些数据,但我甚至不确定绝对是否能正确导出所有内容,因为使用大量的独特形状ID,有成千上万的键作为导出的架构。 (我知道这可能是另一个问题,我只是看到第一种方法的缺点)。

0 个答案:

没有答案