In MongoDB, are sub-documents actually individual BSON documents?

162 views Asked by At

Are sub-documents just a chuck of bits that resides inside a MongoDB BSON document, or are they actually BSON documents linked to its "parent" document?

2

There are 2 answers

0
Gibbs On

Actually, there is no linking. AFAIK, it is considered as single JSON document and stored as BSON in the disk regardless of the nested nature.

This answer will help to understand more about internals such as namespace, data, tree structure, deletion, etc

0
D. SM On

There is no linking. A document is a key-value mapping which may contain submappings. The entire tree is stored as a single entity.

{foo: {bar: 1}}

The {bar: 1} part is an "embedded document" or a "subdocument".

Given:

{foo: {bar: {baz: 2}}}

both {bar: {baz: 2}} and {baz: 2} can be called embedded documents or subdocuments.

The term "BSON document" is ambiguous because it can refer to:

  • A byte sequence of a document as defined above (key-value mapping) serialized to BSON. In this case, the thing that is serialized is the complete entity, the bytes of an embedded document as they exist in BSON aren't by themselves a valid, complete, BSON document.
  • Any key-value mapping that happens to be used in MongoDB-related software, in any format whatsoever including various programming language-native data structures (i.e. not binary which consequently isn't BSON at all).

Strictly speaking the first sense is the correct one but the second sense is commonly used, occasionally causing confusion.