Embedded and references in a data model

I want to create a mongodb database, and use embedded structur. For exemple, consider that the size of each document of the persons 's collection is 16MB. It means that i can not add the sub-document contacts in the person’s collection. 1- In this case what should i do ? 2- If i create the collection of contact, it will be an obligation to reference to the a person. Can we have embeded and reference stuctur in a mongodb database ?

Thank you.

{
    nom:'Kox', 
    prenom:'Karl', 
    gender:'M', 
    addres: 
        {
          rue: '123 Fake Street', 
          appt:108, 
          city:'mycity',
          zip_code:'GGG23'
        }, 
    class: 
        {
          name:'CLASS ONE', 
          group:'C', 
          section:'SECTION ONE' 
        }

}
1 Like

Hi @mixd,

When you say you are considering to embedded the contacts of the user is that all of his contact or a selected portion (favourite, recent etc.)?

If the amount of contacts is small in its document size and in the amount of contacts they can definitely be embedded as an array in the users document. Having said that’s if you cannot control the embedded array size you should use an extended document pattern and move the data to another collection reference the owner,_user_id in its contact document.

Again, I believe that you should access this data in 2 consecutive queries rather then utelizing a join .

Best
Pavel

1 Like

Hi Pavel,

Thank you for your answer and your explanation.

Let me take another example of a social network project, that i want to use embed document model :
Each person can have one or many albums. In the collection of person, we have a sub-document albums(12 fileds). John have 150 albums, and the size of the document of John go over 16MB.
1- In a one-To-Many situation, and to do not go over 16MB for a document, what is the solution ?

Thank you.

1 Like

Hi @mixd,

Well if you need to keep that you can consider the following.

Storing first few albums in his document and then the rest of the outlier pattern in another collection with this user Id as an index reference to those extra album list.

// User document
{
UserId: xxxx
Username : ...,
Albums : [ {
AlbumNama : ...}
...
<Tenth album>
],
TotalAlbums : 150
, 
HasExtended : true
}

//Extended Albums
{
UserId xxx,
Albums : [ {
AlbumNama : ...}
...
<Tenth album>
]
, 
HasExtended : true
}

The idea is when the application will show user xxxx profile it will get the first 10 albums to show on screen and will show a button “see more 140 albums” . When user clicks this button you will fetch any amount of needed indexed documents from extended collection.

This way you will save lots of uneeded data for most users. Keeping the totals is easy with $inc and if you have to keep it acid you can use transactions.

Best
Pavel

2 Likes

Hi @Pavel_Duchovny, thanks a lot for the answer, i understand well.

I understand that also.

Thank you.

1 Like