Documents, Collections, and the Aggregate Boundary

Choose the unit that should be read and changed together

A BSON document is a natural unit for storing a coherent set of fields. A collection groups documents that are queried or managed together. In many designs, a document acts as an aggregate boundary: the data inside it can be read and updated together, and a single-document write is atomic.

For example, a shipping address used only as part of a customer profile may be embedded in the customer document. An order line may be embedded in an order because its quantity, unit price, and selected product description form part of that order's history.

By contrast, inventory shared by many orders is a poor candidate for being duplicated as an independently mutable quantity in every order. Inventory is a separate resource with its own concurrency rules.

Example: customer profile

{
  _id: ObjectId("65a000000000000000000010"),
  email: "asha@example.com",
  name: {
    first: "Asha",
    last: "Rao"
  },
  addresses: [
    {
      label: "home",
      line1: "12 Lake Road",
      city: "Bengaluru",
      postalCode: "560001",
      isDefault: true
    }
  ],
  createdAt: ISODate("2026-01-10T08:00:00Z")
}

This structure works if addresses are part of the profile, are usually fetched with it, and remain within a reasonable size. If addresses become independently permissioned, audited, searched, or unbounded, a separate collection may be more appropriate.

Atomicity boundary

MongoDB guarantees atomicity for an individual document write. If two documents must change as one indivisible business operation, consider whether the model can bring the fields into one document. If not, use a transaction when the operation truly requires multi-document atomicity, and design retry and failure behavior carefully.

Do not enlarge a document merely to avoid transactions. A document boundary should reflect the domain and access patterns, not just an attempt to make every operation single-document.

Specifications & Requirements
  • Document atomicity:A single-document write is atomic.
  • Aggregate boundary:The unit of data that is commonly read and changed together.
Note

Single-document atomicity does not mean every business workflow should be forced into one document. Shared, independently changing, or unbounded data often needs its own collection.

Update related fields atomically within one customer document
db.customers.updateOne(
  { _id: ObjectId("65a000000000000000000010") },
  {
    $set: {
      "name.first": "Asha",
      updatedAt: new Date()
    }
  }
);
Key Takeaways
  • Group fields that have a strong lifecycle and are commonly accessed together.
  • Keep independently changing shared resources separate when duplication would create consistency problems.
  • Use transactions only when cross-document atomicity is required by the business operation.
Knowledge Check

Which data is usually a strong candidate to embed in an order?