MongoDB Document Design and Common Queries

MongoDB stores data as flexible JSON-like documents grouped in collections. Unlike relational tables, a document can hold nested arrays and objects, so related data often lives together instead of being split across joined tables.

The main design question is whether to embed or reference. Embed data that is read together and has a bounded size, such as a customer's shipping addresses. Reference data that grows without limit or is shared widely, such as orders that belong to a customer.

Basic operations from the shell:

bash mongosh "mongodb://localhost:27017/shop"

javascript db.customers.insertOne({ name: "Ana", addresses: [{ city: "Pune" }] }) db.orders.find({ status: "paid" }).sort({ total: -1 }).limit(10) db.orders.createIndex({ status: 1, total: -1 }) db.orders.explain("executionStats").find({ status: "paid" })

The explain("executionStats") call shows whether the query used an index (IXSCAN) or scanned every document (COLLSCAN). Create indexes that match your most frequent filters and sort orders, as with any database.

For writes that must succeed together, use multi-document transactions, but keep them short. Most schemas should be designed so that a single-document update covers the common case.

Also avoid unbounded arrays inside a document. A document has a 16 MB size limit, and an array that keeps growing will slow every update to that document. When a list can grow without limit, store each item as its own document that points back to the parent.