MongoDB Tutorial: Adding A Subdocument To An Existing Document

in STEMGeeks7 days ago

What if we have an existing document or subdocument and we want to add a subdocument to this, or add a subdocument to a subdocument array within a document? In MongoDB: Add Subdocument To Existing Document/Subdocument Array, we look at the steps we can take to do this. The standard SQL equivalent to this is a relationship between tables, where one table references another table for values (such as ratings for products, where both are separated).

In the video, we see that I take an existing document and add a subdocument to it. While the user originally asks, "Why not just use SQL since we'll have to use joins?" we actually see that we don't need to use joins. If the information relates to the document, we can store that relationship within the document in a subdocument. Think of an example where we a collection of documents involving various homes for sale. We want one of the "relationships" to be the past sales' prices for each home. We could use the SQL design where we'd have relationships with tables being joined. But we could also store those prices as a subdocument for each document of a home for sale. There is some nuance about when we may consider this (see the below comment), but it is an option if we've chosen a NoSQL solution.

Design matters here. In some contexts, this would not be appropriate. An example of this might be if we had a ratings subdocument collection of a product or set of products. Depending on what we allow with the ratings, that may become significant in size and we may not want to maintain those subdocuments within the document itself. Some users might leave a rating as long as an epistle and that would become huge if we have enough users doing that. If we restrict ratings to only a rating (no comments), then this type of design may work within the document. The design ultimately matters because some solutions for the design may not be appropriate. As with everything, the more we allow, the more we'll take a hit in performance, scale and possibly security.