So we had a look at the general data structure but always only for one collection and the documents
in that the one collection. Typically you have multiple collections though,
you might have users and products and orders.
So if you have multiple collections that still are related of course or where the documents in these relations
are related,
you obviously have to think about how do you store related data,
do you use embedded documents because that of course is one way of reflecting a relation, if a user
has an address and that address consists of a street and a city,
then you might have a nested address document in the user document
or do you work with references?
Here are two examples,
as I just said, we might have a nested document and an embedded document,
here are my customers
and by the way of course in json, the field names like username, age and so on would be enclosed in double quotation
marks,
I'm just leaving that out here to save some space,
so this is not a real json code but it is structure of the data.
And here, my customer has an address and that address could totally be stored in a new collection
but we can also embed it into our user or into our customer here because it's strongly related to that
customer and we might want to fetch both at the same time or at least have an easy way of fetching both
if we need to.
The alternative is that you use references,
let's say we still have customers and each customer has a list of his favorite books and we could absolutely
go with nested or embedded data.
So here we have an array with embedded documents and each document is shortened here but each document
could be a book with a title, a price, an author and so on.
Now the problem here is that we will have a lot of duplicate data because different customers can have
the same favorite books
and if we then change something about that favorite book, we'll have to change it on all customers,
so instead here, we might go for references. We might have a customers collection and the books collection
and in the customer, we still have that array of favorite books but there, we only store the IDs of the
favorite books.
That means that when we fetch the customers and we also want to fetch the favorite books for
the customer, we have to run two queries, that is correct
but on the other hand if we change a book, we don't have to change it on 10 different customers but only
in the books collection and the ID will never change,
so we never have to change or touch the favorite books array in the customers document,
so we have that relation through a reference.
Now you got these two different approaches and now the obvious question is when should you use which.
Time to have a look at some examples.