Documents, collections and BSON

MongoDB · Essentials · 8 min

Every other MongoDB skill starts from knowing what a document is and how it differs from a table row.

A MongoDB server holds databases; a database holds collections; a collection holds documents. A document is a JSON-like object of field/value pairs, and values can be nested objects or arrays. Collections have no fixed schema by default, so two documents in the same collection may have different fields.

Every document has an _id field that is unique within its collection. If you don't supply one, the driver generates an ObjectId: a 12-byte value containing a timestamp, so it is roughly ordered by creation time.

On disk and on the wire documents are BSON (binary JSON). BSON has more types than JSON, and they matter:

  • ObjectId for ids, Date for timestamps (milliseconds since the epoch, UTC),
  • Int32, Int64 (Long), Double and Decimal128 for numbers (use Decimal128 for money),
  • Binary, Boolean, Null, nested documents and arrays.

A query for { price: 5 } compares by type and value, so the string "5" does not match the number 5. Field order inside a document is preserved, and a single document can be at most 16 MB.

Think of a document as the whole object your application works with, such as an order with its line items embedded, not as one flat row.

Example

// A single document in an "orders" collection
{
  _id: ObjectId("66f1c2a9e4b0a1b2c3d4e5f6"),
  customer: { name: "Ana", email: "ana@example.com" },
  items: [
    { sku: "PEN-01", qty: 3, price: Decimal128("1.50") },
    { sku: "PAD-07", qty: 1, price: Decimal128("4.20") }
  ],
  status: "paid",
  createdAt: ISODate("2026-10-01T09:30:00Z")
}

Remember

  • Database > collection > document; documents are nested JSON-like objects
  • Every document has a unique _id, an ObjectId by default
  • BSON adds real types: Date, ObjectId, Int64, Decimal128
  • Documents are capped at 16 MB

Watch out for

  • Storing dates as strings: you lose date range queries and date operators; store real Date values.

Check yourself

  1. Which document matches the filter { qty: 5 }?
  2. What does MongoDB do if you insert a document without an _id?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.mongodb.com/docs/manual/core/document/

Builds on

Nothing: this is a foundation.

Unlocks