Relations in Document-oriented database?

前端 未结 6 1424
北恋
北恋 2021-02-18 23:14

I\'m interested in document-oriented databases, and I\'d like to play with MongoDB. So I started a fairly simple project (an issue tracker), but am having hard times thinking in

6条回答
  •  一生所求
    2021-02-18 23:58

    The schema design in Document-oriented DBs can seems difficult at first, but building my startup with Symfony2 and MongoDB I've found that the 80% of the time is just like with a relational DB.


    At first, think it like a normal db:

    To start, just create your schema as you would with a relational Db:

    Each Entity should have his own Collection, especially if you'll need to paginate the documents in it.

    (in Mongo you can somewhat paginate nested document arrays, but the capabilities are limited)


    Then just remove overly complicated normalization:

    • do I need a separate category table? (simply write the category in a column/property as a string or embedded doc)
    • Can I store comments count directly as an Int in the Author collection? (then update the count with an event, for example in Doctrine ODM)

    Embedded documents:

    Use embedded documents only for:

    • clearness (nested documents like: addressInfo, billingInfo in the User collection)
    • to store tags/categories ( eg: [ name: "Sport", parent: "Hobby", page: "/sport" ] )
    • to store simple multiple values (for eg. in User collection: list of specialties, list of personal websites)

    Don't use them when:

    • the parent Document will grow too large
    • when you need to paginate them
    • when you feel the entity is important enough to deserve his own collection

    Duplicate values across collection and precompute counts:

    Duplicate some columns/attributes values from a Collection to another if you need to do a query with each values in the where conditions. (remember there aren't joins)

    eg: In the Ticket collection put also the author name (not only the ID)

    Also if you need a counter (number of tickets opened by user, by category, ecc), precompute them.


    Embed references:

    When you have a One-to-Many or Many-to-Many reference, use an embedded array with the list of the referenced document ids (see MongoDB DB Ref).

    You'll need to use an Event again to remove an id if the referenced document get deleted. (There is an extension for Doctrine ODM if you use it: Reference Integrity)

    This kind of references are directly managed by Doctrine ODM: Reference Many


    Its easy to fix errors:

    If you find late that you have made a mistake in the schema design, its quite simply to fix it with few lines of Javascript to run directly in the Mongo console.

    (stored procedures made easy: no need of complex migration scripts)

    Waring: don't use Doctrine ODM Migrations, you'll regret that later.

提交回复
热议问题