【问题标题】:In MongoDB, is it better to dissociate Schemas or put them together?在 MongoDB 中,将 Schema 分离还是将它们放在一起更好?
【发布时间】:2016-11-23 19:13:21
【问题描述】:

以故事为例:一个故事由许多句子组成,在我的情况下,故事永远不会超过 20 个句子。 最好为一个故事制作一个架构,为句子制作另一个架构,最后在 Story 中引用构成故事的句子:

var SentenceSchema = new mongoose.Schema({

  // Some other fields ...

  sentence: {
      type: String,
      validate: validateSentence,
      trim: true
  }

  // Some other fields ...

});    

var StorySchema = new mongoose.Schema({

  // Some other fields ...

  //Sentences of the Story
  sentences: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Sentence'
  }]

  // Some other fields ...

});

或者直接把句子放在故事里更好:

var StorySchema = new mongoose.Schema({

  // Some other fields ...

  //Sentences of the Story
  sentences: [{

    // Some other fields ...

    sentence: {
        type: String,
        validate: validateSentence,
        trim: true
    }

    // Some other fields ...

  }]

  // Some other fields ...

});

对于 20 个句子的故事(最大),为了获得整个故事,对于第一个案例,我们必须进行 20 次连接......效率不高...... 但第二种情况更喜欢可扩展性,例如如果我只想显示一些随机句子,或者更新一个句子......

就我而言,我不认为句子会被其他故事重用,而且故事是逐句写的。我的意思是当一个句子被写入时,它会立即保存在 MongoDB 中。

提前感谢您的任何建议。

【问题讨论】:

    标签: mongodb mongoose database-schema


    【解决方案1】:

    故事中的句子,因为最多只有 20 个 MongoDB是“无连接”的,它必须被用作“无连接”

    当“多”非常大时,您必须为一对多关系使用多个集合

    【讨论】:

      【解决方案2】:

      恕我直言,只要故事的大小符合 bson 文档限制,就将它们嵌入到主文档中。

      这将加快检索过程,还将启用文档级别的 ACID 更新。

      【讨论】:

        【解决方案3】:

        一个句子孤立起来会有意义吗?你能多次重复使用一个句子吗?我认为如果没有故事的上下文,一个句子不太可能有意义,而且你不太可能想要重用一个句子。

        因此故事文档应该由句子子文档组成。 IE。您将有一个集合(故事),每个故事文档将包含一组句子子文档。这将是您展示的第二个架构。

        【讨论】:

        • 有道理。谢谢 :-) 就像@profesor79 说的那样检索会更有效率。
        猜你喜欢
        • 1970-01-01
        • 2010-09-21
        • 2010-09-09
        • 2020-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多