Document structure
Documents can hold nested documents and arrays, so related data can live together.
In this page:
Syntax
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
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
- Creating unbounded arrays
- Using field names that start with $ or contain dots
- 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: