Antoine BERNIER
  • NEW!
    NEW!  Connect Ideas Across Notes
    Save time and share insights. With Paragraph Citation, you can quote others’ work with source info built in. If someone cites your note, you’ll see a card showing where it’s used—bringing notes closer together.
    Got it
      • Create new note
      • Create a note from template
        • Sharing URL Link copied
        • /edit
        • View mode
          • Edit mode
          • View mode
          • Book mode
          • Slide mode
          Edit mode View mode Book mode Slide mode
        • Customize slides
        • Note Permission
        • Read
          • Only me
          • Signed-in users
          • Everyone
          Only me Signed-in users Everyone
        • Write
          • Only me
          • Signed-in users
          • Everyone
          Only me Signed-in users Everyone
        • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invite by email
        Invitee

        This note has no invitees

      • Publish Note

        Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

        Your note will be visible on your profile and discoverable by anyone.
        Your note is now live.
        This note is visible on your profile and discoverable online.
        Everyone on the web can find and read all notes of this public team.

        Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Explore these features while you wait
        Complete general settings
        Bookmark and like published notes
        Write a few more notes
        Complete general settings
        Write a few more notes
        See published notes
        Unpublish note
        Please check the box to agree to the Community Guidelines.
        View profile
      • Commenting
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Suggest edit
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
      • Emoji Reply
      • Enable
      • Versions and GitHub Sync
      • Note settings
      • Note Insights New
      • Engagement control
      • Make a copy
      • Transfer ownership
      • Delete this note
      • Save as template
      • Insert from template
      • Import from
        • Dropbox
        • Google Drive
        • Gist
        • Clipboard
      • Export to
        • Dropbox
        • Google Drive
        • Gist
      • Download
        • Markdown
        • HTML
        • Raw HTML
    Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
    Create Create new note Create a note from template
    Menu
    Options
    Engagement control Make a copy Transfer ownership Delete this note
    Import from
    Dropbox Google Drive Gist Clipboard
    Export to
    Dropbox Google Drive Gist
    Download
    Markdown HTML Raw HTML
    Back
    Sharing URL Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    Customize slides
    Note Permission
    Read
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Write
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: ironhack, lecture, --- <style> .markdown-body img[src$=".png"] {background-color:transparent;} .alert-info.lecture, .alert-success.lecture, .alert-warning.lecture, .alert-danger.lecture { box-shadow:0 0 0 .5em rgba(64, 96, 85, 0.4); margin-top:20px;margin-bottom:20px; position:relative; ddisplay:none; } .alert-info.lecture:before, .alert-success.lecture:before, .alert-warning.lecture:before, .alert-danger.lecture:before { content:"👨‍🏫\A"; white-space:pre-line; display:block;margin-bottom:.5em; /*position:absolute; right:0; top:0; margin:3px;margin-right:7px;*/ } b { --color:yellow; font-weight:500; background:var(--color); box-shadow:0 0 0 .35em var(--color),0 0 0 .35em; } .skip { opacity:.4; } </style> ![Ironhack Logo](https://i.imgur.com/1QgrNNw.png) # MongoDB | Data Models ## Learning Goals After this lesson, you will be able to: - Structure your documents and collections by using data models ## Introduction :::info lecture MongoDB permet une très grande flexibilité dans l'organisation des données et contrairement aux bases de données relationnelles. --- **Nous allons pouvoir imbriquer des objects/tableaux dans un même document.** ![](https://i.imgur.com/zBIjkpH.png) là où en relationnel tout est sur un seul niveau : ![](https://i.imgur.com/DBDjRpo.png) ::: One of the advantages of Mongo is its flexible schema; this allows us to create documents with different structures. Even though we could have some with various fields in the same collection, the most common scenario is that we group the ones with similar properties in the same collection. When designing the data model of a Database we have to consider the types of data that we will use in the application. The key is to comprehend the structure of the documents and how are represented the relationships between them. ## Document Structure :::info lecture En plus d'imbriquer les choses entre elles au sein d'un meme document (**SUBDOCUMENT ou EMBED**) / nous allons également pouvoir faire des liens vers d'autres documents (**REFERENCE**) ![](https://i.imgur.com/GRDKDpb.png) ::: The critical decision in designing data models for MongoDB applications revolves around the structure of documents and how it represents relationships between data. Two tools allow us to show these links: - Referencing documents - Embedding documents Let's look at the two types in depth but first let's understand what **relations** means. ## Referencing documents - Relations References store the relationships between data by including links or references from one document to another. Applications can resolve these references to access the related data. Broadly, these are normalized data models. The relations are associations between documents of different collections through their `_id`. Let's assume we have a `contact` and `access` documents. If we wanted to relate a `contact` and an `access` to a particular `user`, we could simply add a property that relates them through the `user_id`: :::info lecture `user_id` fait ici référence à un document d'une autre collection. C'est son `ObjectId` que l'on référence. ::: ![](https://i.imgur.com/GmBjx9W.png) If we want to get the contact information of a particular user first, we'll get the `_id` of the user, and then we'll make a second query to obtain the contact information based on the `_id` obtained previously. :::info lecture Dans ce exemple, `Willy` est un document, son adresse `123 Fake street` en est un autre distinct. Les 2 sont liés par la propriété `user_id` dans l'adresse. ::: **User** Collection ```javascript { _id: ObjectId("593e7a1a4299c306d656200f"), name: "Willy", lastName: "Doe", email: "willydow@gmail.com", birthday: 1990-12-14 01:00:00.000, phone: "123412399" } ``` **Address** Collection ```javascript { _id: ObjectId("59f30dd86f0b06a96e31bbb9"), user_id: ObjectId("593e7a1a4299c306d656200f"), street: "123 Fake Street", city: "Faketon", state: "MA", zip: "12345" } ``` ## Embedding documents Another way of relating documents is by **embedding them**, saving the related document inside the main one. As you can see in the following picture: :::info lecture Mais grâce à la flexibilité de MongoDB, on peut tout aussi bien "stocker" **des sous-objects dans un meme document** : c'est ce qu'on appelle les sous-documents ou embed-documents. ::: ![](https://i.imgur.com/yrliwPP.png) The same example of using embedded documents: :::info lecture Le même exemple, cette fois-ci : `address` est maintenant un sous-document de `Willy`. ::: ```javascript { _id: ObjectId("593e7a1a4299c306d656200f"), name: "Willy", lastName: "Doe", email: "willydow@gmail.com", birthday: 1990-12-14 01:00:00.000, phone: "123412399", address: { street: "123 Fake Street", city: "Faketon", state: "MA", zip: "12345" } } ``` ### Multiple Sub-documents When we have multiple documents (subdocuments) that can embed in the same component, in this case, `addresses` will be an array of objects. :::info lecture PIRE, ça marche également avec les tableaux : `Willy` contient maintenant 2 sous-documents adresse. ::: ```javascript { _id: ObjectId("593e7a1a4299c306d656200f"), name: "Willy", lastName: "Doe", email: "willydow@gmail.com", birthday: 1990-12-14 01:00:00.000, phone: "123412399", addresses: [ { street: "123 Fake Street", city: "Faketon", state: "MA", zip: "12345" }, { street: "1 Some Other Street", city: "Boston", state: "MA", zip: "12345" } ] } ``` :::danger lecture Il est à noter que les documents (principaux) ont une limite de taille 16Mb. ::: :::warning :bomb: Be aware of how many subdocuments you embed into a single one. **Keep in mind that a document in Mongo cannot be more than 16Mb in size.** ::: ## Defining Your Document Schema :::info lecture Tout l'art va donc d'être d'architecturer ses données en choisissant entre embed et reference. Chacune aura ses avantages et ses inconvénients... ![](https://i.imgur.com/HsZUh4I.png) ![](https://i.imgur.com/5wWuI8e.png) ::: You should start the schema design process by considering the application’s query requirements. You should model the data in a way that takes advantage of the document model’s flexibility. :::warning :cactus: Perhaps one of the more difficult parts of Mongo is designing the structure of our data. To do this efficiently, we will need to know how the application will use the database, what data we want to get, how often we get that data, what size the documents can be, etc. ::: Let's take a look at some patterns! ### Model One-to-One Relationships with Embedded Documents Consider the same example that maps `patron` and `address` relationships. The example illustrates the advantage of embedding over referencing if you need to view one data entity in the context of the other. In this one-to-one relationship between `patron` and `address` data, the `address` belongs to the `patron`. In the normalized data model, the `address` document contains a reference to the `patron` document. :::info lecture Dans cet ex de referencing, si notre application a souvent/toujours besoin des 2 informations en même temps... ::: ```javascript { _id: ObjectId("593e7a1a4299c306d656200f"), name: "Joe Bookreader" } { patron_id: ObjectId("593e7a1a4299c306d656200f"), street: "123 Fake Street", city: "Faketon", state: "MA", zip: "12345" } ``` If we frequently retrieve the address data with the name information, then with referencing, your application needs to issue multiple queries to resolve the reference. The better data model would be to embed the address data in the patron data, as in the following document: :::info lecture Il sera alors plus "judicieux" d'opter pour l'embeding : ::: ```javascript { _id: ObjectId("593e7a1a4299c306d656200f"), name: "Joe Bookreader", address: { street: "123 Fake Street", city: "Faketon", state: "MA", zip: "12345" } } ``` :::info lecture 👌En effet, accéder aux 2 informations ne fera l'objet que d'une seule requête (et non plus 2). ::: **With the embedded data model, your application can retrieve the complete patron information with one query.** ### Model One-to-Many Relationships with Embedded Documents Following the same example, it illustrates the advantage of embedding over referencing if you need to view many data entities in the context of another. In this one-to-many relationship between `patron` and `address` data, the `patron` has multiple `address` entities. In the normalized data model, the `address` documents contain a reference to the `patron` document. :::info lecture Ceci est d'autant plus vrai si les adresses sont multiples... ::: ```javascript { _id: ObjectId("593e7a1a4299c306d656200f"), name: "Joe Bookreader" } { patron_id: ObjectId("593e7a1a4299c306d656200f"), street: "123 Fake Street", city: "Faketon", state: "MA", zip: "12345" } { patron_id: ObjectId("593e7a1a4299c306d656200f"), street: "1 Some Other Street", city: "Boston", state: "MA", zip: "12345" } ``` If your application frequently retrieves the address data with the name information, then your application needs to issue multiple queries to resolve the references. A more optimal schema would be to embed the address data entities in the patron data, as in the following document: :::info lecture Nous obtenons ici toutes les infos en 1 seule requête, contrairement à 3. ::: ```javascript { _id: ObjectId("593e7a1a4299c306d656200f"), name: "Joe Bookreader", addresses: [ { street: "123 Fake Street", city: "Faketon", state: "MA", zip: "12345" }, { street: "1 Some Other Street", city: "Boston", state: "MA", zip: "12345" } ] } ``` **With the embedded data model, your application can retrieve the complete patron information with one query.** ### Model Many-to-Many Relationships with Document References :::info lecture Cependant, n'opter que pour l'embeding peut avoir également des inconvénients... ::: Consider the following example that maps `publisher` and `book` relationships. The example illustrates the advantage of referencing over embedding to avoid repetition of the `publisher` information. Embedding the `publisher` document inside the `book` document would lead to the repetition of the `publisher` data, as the following documents show: :::info lecture Ici par ex, le `publisher` étant embed, cette information est dupliquée entre les livres. Si nous voulons mettre à jour notre publisher, il nous faudra le faire dans chacun des livres le portant : ::: ```javascript { title: "MongoDB: The Definitive Guide", author: [ "Kristina Chodorow", "Mike Dirolf" ], published_date: ISODate("2010-09-24"), pages: 216, language: "English", publisher: { name: "O'Reilly Media", founded: 1980, location: "CA" } } { title: "50 Tips and Tricks for MongoDB Developer", author: "Kristina Chodorow", published_date: ISODate("2011-05-06"), pages: 68, language: "English", publisher: { name: "O'Reilly Media", founded: 1980, location: "CA" } } ``` To avoid repetition of the `publisher` data, use references and keep the `publisher` information in a separate collection from the `book` collection. :::info lecture Il serait ici plus judicieux de stocker nos publishers dans une collection propre, et de les lier en référence dans nos livres. ::: ```javascript { _id: ObjectId("593e7a1a2312c306d321323g"), name: "O'Reilly Media", founded: 1980, location: "CA" } { _id: ObjectId("593e7a1a4299c306d656200f"), title: "MongoDB: The Definitive Guide", author: [ "Kristina Chodorow", "Mike Dirolf" ], published_date: ISODate("2010-09-24"), pages: 216, language: "English", publisher_id: ObjectId("593e7a1a2312c306d321323g") } { _id: ObjectId("593e7b2b4299c306d656299d"), title: "50 Tips and Tricks for MongoDB Developer", author: "Kristina Chodorow", published_date: ISODate("2011-05-06"), pages: 68, language: "English", publisher_id: ObjectId("593e7a1a2312c306d321323g") } ``` --- When using references, the growth of the relationships determines where to store it. If the number of books per `publisher` is small with limited growth, storing the `book` reference inside the `publisher` document may sometimes be useful. Otherwise, if the number of books per `publisher` is unbounded, this data model would lead to mutable, growing arrays, as in the following example: ```javascript { name: "O'Reilly Media", founded: 1980, location: "CA", books: [123456789, 234567890, ...] } { _id: ObjectId("593e7a1a4299c306d656200f"), title: "MongoDB: The Definitive Guide", author: [ "Kristina Chodorow", "Mike Dirolf" ], published_date: ISODate("2010-09-24"), pages: 216, language: "English" } { _id: ObjectId("593e7b2b4299c306d656299d"), title: "50 Tips and Tricks for MongoDB Developer", author: "Kristina Chodorow", published_date: ISODate("2011-05-06"), pages: 68, language: "English" } ``` ## Independent Practice (10 min) Let's practice modeling! Here you have some common problems. Please pair with another student and propose how to implement the schema for the following scenarios. :::warning In this exercise, deciding what fields go into which collection is less important. Focus on deciding whether to **use relations** or **embed documents**. ::: ### Twitter - Users - Tweets - Followers - Favorites :::info lecture [![](https://docs.google.com/drawings/d/e/2PACX-1vQPW4-sojYAiUmACSTpSDqTIAFhzysRtfYHf8Liipt8DXVOrtBEBd4pE_9k0wbWH1WXTmYvKEg9iV37/pub?w=1370&h=556)](https://docs.google.com/drawings/d/1BRjRieiYRmLoqsCzz_mEeWsSdvjfBw8XcpUP9nbYqYg/edit?folder=0AAQNm5fx5y30Uk9PVA) ::: ### Airbnb - Users - Homes - Bookings - Reviews ### Spotify - Users - Artists - Songs - Albums - Genres - Favorites ## Summary In this lesson, we learned how to design databases using embedded documents and relations. ## Extra Resources Here you have interesting articles if you want to learn more about designing documents. - [6 Rules of Thumb for MongoDB Schema Design: Part 1](http://blog.mongodb.org/post/87200945828/6-rules-of-thumb-for-mongodb-schema-design-part-1) - [6 Rules of Thumb for MongoDB Schema Design: Part 2](http://blog.mongodb.org/post/87892923503/6-rules-of-thumb-for-mongodb-schema-design-part-2) - [Thinking in Documents: Part 1](https://www.mongodb.com/blog/post/thinking-documents-part-1?jmp=docs) - [Thinking in Documents: Part 2](https://www.mongodb.com/blog/post/thinking-documents-part-2) - [Data Modeling Article](https://www.infoq.com/articles/data-model-mongodb)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully