MongoDB – Document structure and relations

Document structure:

MongoDB will represent relationships between documents with:

  • Embedded data – The whole document can be retrieved in a single query like this. The drawback is that if the embedded document keeps on growing too much in size, it can impact the read/write performance. The document max size is 16MB.
  • Manual References – similar with FK in RDBMS. It is the approach of designing normalized relationship.
  • Database References – a document references documents from many collections.

Below some examples with each type of representation applied to different relations.

One To One Relations:

One to Many relations:

Many to Many relations:

Note: It’s recommended to use multiple key indexes (compound index) to make queries against embedded documents efficient.

Benefits of Embedding:

  • Improvement read performance
  • One round trip to the database

Database References:

There are three fields in DBRefs:

  • $ref: This field specifies the collection of the referenced document
  • $id: This field specifies the _id field of the referenced document
  • $db: This is an optional field and contains name of the database in which the referenced document lies

Unless you have a compelling reason (if you need to reference documents from multiple collections) to use DBRefs, use manual references instead.

The custDetails DBRef field here specifies that the referenced customer document lies in customerName collection under customers database and has an id of 56868a99a1de4cd4b08a25ab.

The following code dynamically looks in the collection specified by $ref parameter (custDetails in our case) for a document with id as specified by $id parameter in DBRef.

 Additional links:
  1. https://docs.mongodb.org/manual/applications/data-models-relationships/