M320: Chapter 2: Relationships

MongoDB Relationships

Introduction

One customer -> (One to many) Many Invoices
Invoices <- (Many to Many) -> Products

Should the information be embedded or referenced?

Tabular Databases(relational) and MongoDB.

Relationship Types and Cardinality

Common Relationships(in relational database world)

  • one-to-one(1-1)
  • one-to-many(1-N)
  • many-to-many(N-N)

one-to-one
A customer has one customer_id.

one-to-many(1-N)
A customer has many invoices.

many-to-many(N-N)
An invoice contains many products.
Each product is contained in many invoices.

[min, likely, max]

If you know that you are traversing a huge relationship, you may want to represent it differently or be more careful about how you write queries when handling the zillions side of this side of the relationship. Large numbers were rarely a consideration in the past, however, they became a serious consideration when dealing with big data. Because there is no graphical notation in the crow’s foot notation for this kind of a relationship, we added one.

One-to-Many Relationship

The address is embedded in the order, if a user change his address, it does not affect the orders that have delivered.

If they are most often queried documents, using embed, if the embeded data is samll.

Many-to-Many Relationship

One-to-One Relationship

Problem:

Which of the following are valid ways to represent a one-to-one relationship with the document model in MongoDB?

  • Embed the fields as a sub-document in the document.
  • Embed the fields in the document.
  • Link to a single document in another collection.

Lab: One-to-One Relationship

One-to-Zillions Relationship

Which of the following statements are true about one-to-zillions relationships?

  • We must take extra care when writing queries that retrieve data on the zillions side.
  • It is a special case of the one-to-many relationship.
  • The relationship representations that embed documents are not recommended.

相关文章: