jl.
jl.

Reputation: 2239

MongoDB Schema Design - New Collection or Reference?

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.

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?

What would be a better way to do it?

// db.courses
{ name: Biology, cat: 1 }
{ name: English, cat: 2 }

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

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

Thank you.

Upvotes: 2

Views: 2378

Answers (1)

Andrew Orsich
Andrew Orsich

Reputation: 53705

Introduction:

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.

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.

Answer:

So in your case i suggest two ways:

  1. Create enumeration for categories and get category name by id( but not load from mongo).
  2. Just copy category name in course( But first case better because in case if category name was changed your need update each course with new category name).

Upvotes: 3

Related Questions