← Back to MongoDB Course | Chapter 2: CRUD — Create | Lesson 3 of 7

Document structure

Documents can hold nested documents and arrays, so related data can live together.

In this page:

  1. Document structure
Syntax
javascript
db.collection_name.insertOne({
  field: value,
  subdocument: { key: value },
  array: [value1, value2]
})

Document structure

Embed sub-documents for data that belongs to the parent and arrays for lists of values or small sets of objects. Field names are strings, and dotted paths reach into nested data. A document can be up to 16 MB, so unbounded arrays are risky.

Note: Keep documents well under the 16 MB limit and avoid arrays that grow forever.

Example: Document structure

bash
test> db.orders.insertOne({
...   _id: 100,
...   customer: { name: "Ada", email: "[email protected]" },
...   items: [{ sku: "PEN", qty: 2, price: 3 }, { sku: "LAMP", qty: 1, price: 45 }],
...   status: "paid"
... })
{ acknowledged: true, insertedId: 100 }
test> db.orders.findOne({ "customer.name": "Ada" }, { status: 1, "items.sku": 1 })
{
  _id: 100,
  items: [ { sku: 'PEN' }, { sku: 'LAMP' } ],
  status: 'paid'
}

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Creating unbounded arrays
  2. Using field names that start with $ or contain dots
  3. Deeply nesting without a query need
Chapter Summary
  • Embed related data
  • Arrays hold lists
  • Dotted paths reach nested fields
  • Documents are limited to 16 MB
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.