Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 70 ยท Documents and BSON

Documents, JSON and Field Types

Learn how MongoDB documents are structured: fields, nested objects, arrays, field-name rules, the 16 MB size limit and how a document compares with a table row.

Everything in MongoDB is built from one idea: the document. A document is an ordered set of field: value pairs, written like a JSON object. It is the unit you insert, read, update and delete, and the unit MongoDB guarantees to change atomically. If you understand what a document can contain and where its limits are, the rest of the tutorial becomes much easier.

In this lesson you will see how documents nest objects and arrays, how field names work, which size limits exist, why field order sometimes matters, and how a document differs from a row in a relational table. The previous lesson, The Practice Engine Used in This Tutorial, explains the stand-ins that run the examples.

Anatomy of a document

Fields Name and value pairs, in order.
Nested objects A value can be another document.
Arrays A value can be a list of anything.
_id A unique key for the document.
1 / 2

A document in detail

Here is a realistic document, an order for an online shop:

JavaScript
{
  _id: 1001,
  status: "paid",
  placed: "2026-03-01",
  customer: { id: 7, name: "Mia", address: { city: "Lisbon", country: "PT" } },
  items: [
    { sku: "A1", name: "Trail Shoe", qty: 1, price: 89 },
    { sku: "B2", name: "Water Bottle", qty: 2, price: 14 }
  ],
  tags: ["gift", "express"],
  note: null
}

Four kinds of values appear here:

  • Scalars: strings, numbers, booleans and null. (Real MongoDB also has dates, ObjectId and more, see BSON Types.)
  • Embedded documents: customer is an object, and it contains another object, address.
  • Arrays: items is an array of documents and tags is an array of strings. An array can mix types, although doing that is rarely a good idea.
  • null: a field that exists and has no value, which is different from a field that is missing (more in BSON Types).

The paths to values are written with dots: customer.address.city and items.0.sku (the number is an array position). Querying Nested Fields and Arrays is entirely about these paths.

The first stand-in prints every path in a document together with the type of the value found there. It is a good way to see a document the way a query sees it.

JS Every path in a document

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the items rows: the array has positions 0 and 1, and each position holds an object with its own fields. This is how you can address "the price of the first item" as items.0.price.

Field names and values

Field names are strings. These habits keep documents trouble-free:

  • Use plain, consistent names: letters, digits and underscores, in one style such as camelCase or snake_case.
  • Avoid dots in names, because dots are how paths are written. A field called a.b is confusing to query and to update.
  • Avoid names that start with $, which looks like an operator. Recent MongoDB versions allow some such names, but tools and operators treat them awkwardly.
  • Do not rely on duplicate field names. A document is meant to hold each field once.
  • Do not use data as field names (for example one field per product SKU). Names like that cannot be indexed sensibly. Use an array of { k, v } pairs instead, a technique called the attribute pattern in Schema Design Patterns.
  • The _id field is special. It must be unique in the collection and is always indexed (_id and ObjectId).

MongoDB also keeps field order. Fields are stored in the order you wrote them, except that _id is placed first when MongoDB adds it. Order rarely matters, but one case surprises people: comparing an embedded document for equality is order-sensitive.

JS Embedded documents compare in order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real MongoDB behaves the same way: db.shoes.find({ size: { eu: 42, us: 9 } }) matches only documents whose size has exactly those fields in exactly that order. This is why you query individual fields with dot notation, as in { "size.eu": 42 }, instead of matching a whole subdocument.

Size limits

A single document can be at most 16 mebibytes (16 MiB) of BSON. Documents can also nest at most 100 levels deep. For most data you will never come near either. 16 MiB is a lot of text, but it is not much for a document that keeps growing, for example an array that gets one new element per click forever.

When a document grows without bound, the failure is not only the hard limit. Large documents are expensive to read, to send and to rewrite: updating one small field in a 10 MB document still moves much more data than updating a small document. The usual fixes are to store the growing items in a separate collection and reference them, or to bucket them in groups (Schema Design Patterns). Files larger than 16 MiB go into GridFS or an object store, not into one document.

The next stand-in estimates a document's size from its JSON text (BSON is a bit different, so treat it as a rough guide) and shows a user document that grows with every login event.

JS A document that grows without bound

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You can see that the document becomes a problem long before the limit: a hundred thousand login events already make it about 9 MB in this estimate, and every update to the user risks rewriting a large document. The better design keeps recent logins in the user document and older ones in a logins collection.

Documents versus table rows

Relational row MongoDB document
Shape Fixed columns per table Flexible fields per document
Nesting Flat (use more tables) Objects and arrays inside
Related data Separate tables, joined Often embedded
Missing data A column holding NULL Field can simply be absent
Unit of atomicity A row (or a transaction) One document
Key Primary key _id

A row is a flat record, and a document is a tree. If you enjoyed normalising data in SQL, notice that embedding is the opposite instinct: instead of splitting orders and order_items and joining them, you keep items inside the order. That choice is covered in Embedding vs Referencing.

JSON versus BSON

You write documents as JSON-like text, but MongoDB stores and transmits BSON, a binary format. JSON has only a few types: string, number, boolean, null, array and object. BSON adds the types a database needs, such as dates, ObjectId, 32-bit and 64-bit integers, decimals and binary data. It also stores lengths up front so that servers can skip through documents quickly. BSON Types is the next lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which dot path addresses the price of the first element of the items array?

    MongoDB paths use dots, and array positions are written as numbers: items.0.price.
  2. 2. A document has size: { eu: 42, us: 9 }. Does the filter { size: { us: 9, eu: 42 } } match it?

    Equality on an embedded document compares fields in order. Use dot notation such as { 'size.eu': 42 } to avoid the problem.
  3. 3. What is the maximum size of a single MongoDB document?

    A document can be at most 16 MiB of BSON. Larger data needs another design, such as separate documents or GridFS.
  4. 4. Why is an array that gets a new element on every event, forever, a bad design?

    Unbounded growth makes each update heavier and risks the 16 MiB limit. Store the items in their own collection or in buckets.

Summary

  • A document is an ordered set of fields whose values can be scalars, embedded documents and arrays.
  • Paths to nested values use dots: customer.address.city, items.0.price.
  • Use simple, consistent field names. Avoid dots and a leading $, and do not store data in field names.
  • Equality on a whole embedded document depends on field order, so prefer dot notation.
  • A document is limited to 16 MiB and 100 nesting levels. Unbounded arrays are a design smell long before the limit.
  • A document is a tree and the unit of atomic change. A relational row is flat.
  • You write JSON-like text, but MongoDB stores BSON with extra types.

Next, look at the types behind the values in BSON Types.