mongodb best practice: nesting

后端 未结 4 715
盖世英雄少女心
盖世英雄少女心 2020-12-30 08:06

Is this example of nesting generally accepted as good or bad practice (and why)?

A collection called users:

user
    basic
        name : value
              


        
相关标签:
4条回答
  • 2020-12-30 08:19

    In my experience, I've never found any "best practices" for what a MongoDB record actually looks like. The question to really answer is, "Does this MongoDB schema allow me to do what I need to do?"

    For example, if you had a list of addresses and needed to update one of them, it'd be a pain since you'd need to iterate through all of them or know which position a particular address was located. You're safe from that since there is a key-value for each address.

    However, I'd say nix the basic and contact keys. What do these really give you? If you index name, it'd be basic.name rather than just name. AFAIK, there are some performance impacts to long vs. short key names.

    Keep it simple enough to do what you need to do. Try something out and iterate on it...you won't get it right the first time, but the nice thing about mongo is that it's relatively easy to rework your schema as you go.

    0 讨论(0)
  • 2020-12-30 08:19

    That is acceptable practice. There are some problems with nesting an array inside of an array. See SERVER-831 for one example. However, you don't seem to be using arrays in your collection at all.

    Conversely, if you were to break this up into multiple collections, you would have to deal with a lack of transactions and the resulting race conditions in your data access code.

    0 讨论(0)
  • 2020-12-30 08:20

    You may want to take a look at schema design in MongoDB, and specifically the advice on embedding vs. references.

    Embedding is preferred as "Data is then colocated on disk; client-server turnarounds to the database are eliminated". If the parent object is in RAM, then access to the nested objects will always be fast.

    0 讨论(0)
  • 2020-12-30 08:23

    In my opinion above schema not 'generally accepted', but looks like great. But i suggest some improvements thats will help you to query on your document in future:

    User
        Name 
        Url
        Emails {email, emailType(primary, secondary)}
        Addresses{address, city, state, postalcode, country, language}
    

    Nesting is always good, but two or three level nesting deep can create additional troubles in quering/updating.

    Hope my suggestions will help you make right choice of schema design.

    0 讨论(0)
提交回复
热议问题