MongoDB模式设计-新集合还是参考? [英] MongoDB Schema Design - New Collection or Reference?

查看:89
本文介绍了MongoDB模式设计-新集合还是参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到一个有关MongoDB模式的问题.参考 MongoDB Schema Design 上的示例,关于db.students和db.courses.

I bumped into a question regarding the schema for MongoDB. With reference to the example on MongoDB Schema Design, regarding the db.students and db.courses.

由于我更习惯于使用SQL结构化结构,因此我仍然对该引用或嵌入问题感到困惑.因此,该示例仅显示了db.students中的路线,并引用了db.courses.因此,如果要对我的课程进行分类,例如humanitieslanguages等,该怎么办?

As I am more used to SQL structured, I am still confused with this reference or embed problem. So, the example is only showing the course within the db.students, is referenced to the db.courses. So if I were to categorize my courses such as humanities, languages, etc, how should I do it?

有什么更好的方法呢?

    1.创建一个名为db.categories的集合,并引用它的db.courses吗?
    1. create a collection called `db.categories` and reference the db.courses to it?
// db.courses
{ name: Biology, cat: 1 }
{ name: English, cat: 2 }

// db.categories
{ cat: 1, name: Humanities }
{ cat: 2, name: Languages }

    2.仅仅嵌入课程中?

      2. to just embed within the courses?

      // db.courses
      { name: Biology, cat: Humanities }
      { name: English, cat: Languages }
      { name: History, cat: Humanities }
      

      任何人都可以请指教,我该怎么办?

      Could anyone please kindly advise, what should I be doing?

      谢谢.

      推荐答案

      简介:

      在您的情况下,这两种变体都将是不错的选择,因为类别仅是枚举,而您不需要加载类别即可显示课程,您只需要创建一些枚举并通过ID获取类别名称即可.

      In yours case both variants will be good because category just enumeration an you don't need load category in order to display course, you just need create some enumeration and get category name by id.

      但是例如,如果您有表db.users,并且每个用户都有db.courses的集合,则不需要创建单独的文档,而只需要嵌套的集合课程.这真的很酷,因为在sql中,您需要创建具有一对多引用的单独表.

      But in for example if you have table db.users and each user have collection of db.courses you don't need create separate document your just need nested collection courses. And it's really cool because in sql you need create separate table with one to many reference.

      文档数据库的一大好处是,您可以创建带有嵌套集合的大型文档,而无需联接表.

      The one big benefit of document database is that you can create big documents with nested collections and no need to join tables.

      答案:

      因此,在您的情况下,我建议两种方法:

      So in your case i suggest two ways:

      1. 为类别创建枚举并通过id获取类别名称(但不会从mongo加载).
      2. 只需在课程中复制类别名称(但最好是第一种情况,因为如果类别名称被更改,则您需要使用新的类别名称更新每门课程).

      这篇关于MongoDB模式设计-新集合还是参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆