Back to all posts

MongoDB Schema Design Best Practices for 2026

For developers laying out MongoDB collections for an application; embedding, references, indexes and validation rules are explained on one small example database.

On this page

Without a validation rule, MongoDB saves any document you insert, right or wrong. A good schema starts from the queries. Embed what you read together and what stays small. Use a reference for what grows without limit or is read on its own. Then index the fields you filter and sort on, and add a validation rule so that MongoDB refuses documents of the wrong shape.

The sample data is a shop database with three collections. In mongosh, these statements insert one document into each:

db.customers.insertOne({
  _id: ObjectId("65a000000000000000000001"),
  first_name: "Ana",
  email: "[email protected]",
  address: { street: "12 Rue Victor Hugo", city: "Lyon", country: "France" }
})

db.products.insertOne({
  _id: ObjectId("65a000000000000000000101"),
  name: "Desk lamp",
  price: 40
})

db.orders.insertOne({
  _id: ObjectId("65a000000000000000001001"),
  customer_id: ObjectId("65a000000000000000000001"),
  order_date: ISODate("2026-11-02T00:00:00Z"),
  status: "shipped",
  items: [
    { product_id: ObjectId("65a000000000000000000101"), quantity: 2, unit_price: 40 }
  ]
})

The address is embedded in the customer document, and the items are embedded in the order. The order points to its customer through customer_id, and each item points to its product through product_id. Both fields are references.

The customers, orders and products collections: address is embedded in customers, the items array is embedded in orders, and dashed arrows run from orders.customer_id to customers._id and from items.product_id to products._id

Design around your queries

List the reads your application runs most often before you decide anything. For the shop, they are: show a customer with the address, show an order with its items, and list a customer's orders, newest first. When one read always needs some data together, store that data in one document.

Four questions decide between embedding and a reference:

QuestionEmbedReference
How big can the related data get?small and boundedlarge or unbounded
How often does it change?rarelyoften
Is it read with the parent?alwaysoften on its own
How many per parent?one or a fewmany

Where the answers disagree, the size question decides. A BSON document can't grow past 16 mebibytes, and the write that crosses the limit fails.

A write to one document is atomic: MongoDB applies it completely or not at all, embedded documents included. An atomic change across documents needs a transaction. MongoDB's manual says that a transaction should not replace good schema design.

When to use embedded documents

Embed data that is small, bounded and read with its parent. Each customer has one address of three fields, and every order screen shows the items. To query a field of an embedded document, write its dotted path in quotes:

db.customers.find({ "address.city": "Lyon" })

The same dotted path works in an index, and so does a path into an array of documents:

db.customers.createIndex({ "address.city": 1 })
db.orders.createIndex({ "items.product_id": 1 })

The second index is on a field inside the items array. MongoDB makes this index a multikey index automatically: the index holds a key for each array element. That index serves a query such as { "items.product_id": ObjectId("65a000000000000000000101") }. The query matches every order with at least one item for that product.

Each item also holds a copy of the product's price in unit_price. The copy is on purpose. When the product's price changes, the order still shows the price that the customer paid. The manual calls such copies temporal duplicate data. The manual's own example is a customer's address at the time of an order.

Avoid deeply nested structures

MongoDB allows 100 levels of nesting, and each object or array adds a level. The positional operator $ updates the array element that the query matched. The operator $ can't reach an array that sits inside another array.

To update an array inside an array, use the filtered positional operator $[<identifier>] with an arrayFilters option. Data that needs this operator usually belongs in a collection of its own. For more on querying and indexing such data, read Embedded documents and arrays.

When to use references

Use a reference for data that grows without limit, and for data that is read on its own. A customer keeps placing orders for as long as the account exists. If the orders were embedded in the customer document, they would form an unbounded array. Such an array slows down the indexes on the array, and pushes the customer document toward 16 mebibytes.

So orders get their own collection. Products stay in their own collection too, because many orders share one product. To read an order with its customer, join them with $lookup:

db.orders.aggregate([
  { $match: { _id: ObjectId("65a000000000000000001001") } },
  { $lookup: { from: "customers", localField: "customer_id", foreignField: "_id", as: "customer" } }
])

$lookup adds the array field customer to the order. This array holds the customers whose _id equals the order's customer_id. The array is empty when no customer matches. The manual recommends an index on the foreignField, here _id, which always has an index.

MongoDB doesn't check a reference. According to the manual, your application keeps references consistent and handles a reference to a missing document.

Index the fields you query

An index speeds up the reads that use it. In exchange, the index takes memory, and keeping it up to date slows writes. Index the fields that your frequent queries filter and sort on. The listing of a customer's orders, newest first, is one such query:

db.orders.find({ customer_id: ObjectId("65a000000000000000000001") }).sort({ order_date: -1 })
db.orders.createIndex({ customer_id: 1, order_date: -1 })

The order of the fields in the index follows the manual's ESR guideline: fields matched for equality first, then fields you sort on, then fields filtered by a range. customer_id is matched for equality, so it comes first, and order_date is the sort. With an equality match on the first field, the index can return the orders already sorted by the second.

To find indexes that nothing uses, run $indexStats:

db.orders.aggregate([ { $indexStats: {} } ])

The aggregation returns a document for each index, where accesses.ops counts the user operations that used the index. Read the count after the server has run a normal workload. The count resets when mongod, the server process, restarts.

Add a validation rule

A validation rule makes MongoDB refuse documents of the wrong shape. You write the rule as a $jsonSchema and attach it to the collection. The collMod command adds a rule to a collection that already exists:

db.runCommand({
  collMod: "orders",
  validator: { $jsonSchema: {
    bsonType: "object",
    required: [ "customer_id", "order_date", "status", "items" ],
    properties: {
      customer_id: { bsonType: "objectId" },
      order_date:  { bsonType: "date" },
      status:      { enum: [ "pending", "shipped", "delivered" ] },
      items: {
        bsonType: "array",
        minItems: 1,
        items: { bsonType: "object", required: [ "product_id", "quantity" ] }
      }
    }
  } }
})

From then on, MongoDB rejects an insert or update of an order without customer_id, or with a status outside the three values. Each document already in the collection is checked the next time it is modified.

The validation level sets which writes MongoDB checks. The default, strict, checks every insert and update, and moderate skips updates to documents that were already invalid.

The validation action sets what happens to a bad write. The default, error, rejects the write, and warn saves the write and records the violation in the log.

When your documents change shape in a later release, a schemaVersion field tells the application how to read each document. The manual calls such a field the schema versioning pattern.

Common mistakes to avoid

The manual keeps a list of schema design anti-patterns, designs that the manual advises against. The first is the unbounded array, which the separate orders collection avoids. Another is the bloated document. In a bloated document, some fields are stored together but not read together. Those fields cost RAM and bandwidth whenever the document is read.

Too many collections are a mistake as well. Each extra collection carries its own _id index. If you lay out the collections like relational tables, each read of related data needs a $lookup. Unnecessary indexes take disk space and slow writes. One more mistake is a field whose type changes between releases, such as a string in old documents and an object in new ones. Every query then has to handle both types. A bsonType in the validation rule fixes the field's type, and MongoDB then rejects the first write that uses another type.

See and document the schema in DbSchema

DbSchema connects to MongoDB and reads documents of each collection to find the fields: by default, 100 documents from the start and 100 from the end. To read more documents, up to all of them, change Schema Scan Depth in the connection's settings.

DbSchema lists every field, nested document and array that it finds, each with its type. The list is an approximation, built from the documents that DbSchema has read. MongoDB enforces none of this list.

A MongoDB shop database as a DbSchema diagram: customers with the nested document address, orders with the array items, and products, joined by relations

The shop database in this screenshot comes from the DbSchema documentation. It has more fields than the sample data above, and it stores prices as strings.

Where a collection has a $jsonSchema validator, DbSchema reads the fields from the validator instead of the documents. After the collMod above, orders is such a collection. Without a validator, the Edit Collection dialog shows Inferred ( no validation ) ticked.

While DbSchema is connected, a change that you confirm in Edit Collection changes both the database and the model, DbSchema's copy of the schema. To write every validator of the model to MongoDB, choose Database → Create or Upgrade the Collection Validators into the Database.

The DbSchema Edit Collection dialog for orders, with Inferred ( no validation ) ticked and the fields _id, customer_id, order_date, status and the array items

MongoDB declares no relations between collections, so DbSchema compares field values. Where a field such as orders.customer_id holds the _id of a document in another collection, DbSchema draws a line.

These lines are virtual relations: they live in the DbSchema model file, and MongoDB never sees them. For a reference that DbSchema didn't find, drag the field onto the field it refers to.

The Data Explorer of DbSchema follows those relations. In DbSchema, right-click the customers header and choose Data Explorer. Then click the arrow next to the collection name and choose Cascade orders via Relationship. When you select a customer, the orders pane shows that customer's orders. Each pane can follow the next relation in the same way.

The DbSchema Data Explorer with a customer document on the left and, joined by a line, the first of her two orders on the right

In DbSchema's Edit Collection dialog, write what the collection holds as its Comment, and what each field holds as its Description. Then choose File → Export As... → HTML5/PDF Documentation.

The HTML5 documentation is a single .html file that opens in any browser. With Diagram Vector Image ticked, DbSchema draws the diagram as an SVG image. With Image Mouse-Over Tooltips ticked, the page shows each comment when you point at its field.

Download DbSchema at https://dbschema.com/download.html, connect it to your MongoDB database, and look at the diagram before you change a collection. Connecting, reverse-engineering (reading the collections into a model) and the diagram are in the free Community Edition. Saving the model file, following relations in the Data Explorer, and the HTML5 documentation are part of DbSchema Pro.

Design MongoDB collections visually

DbSchema samples your documents, draws the collections as an interactive diagram, and records the virtual relations MongoDB never declares. Reverse-engineering and interactive diagrams are in the free Community Edition.