MongoDB Data Modeling
What Is Data Modeling?
Data modeling is deciding how your information is shaped into documents and collections. MongoDB has a flexible schema, so the guiding rule is: structure data the way your application reads and writes it. The two core choices are embedding related data inside one document and referencing it from another collection by _id. Related data that is read together and has a bounded size is usually a good candidate for embedding.
Why It Matters
| Reason | Benefit |
|---|---|
| Fewer round trips | Embedded data comes back in a single read with no join. |
| Atomic updates | Changing a parent and its embedded children is one atomic write. |
| Controlled growth | Referencing keeps documents small when child data keeps growing. |
| Avoids duplication problems | Referencing shared data means one update fixes it everywhere. |
| Better performance | A model that fits your queries needs fewer indexes and less work. |
How To Use It
- List the main screens or API calls of your application and the data each one needs.
- Group data that is read together; mark those relationships as embed candidates.
- Check each relationship: how many children, and does the number keep growing?
- Embed bounded children; reference unbounded or independently updated ones.
- For references, store the parent _id on the child and index it.
- Prototype in mongosh with a few realistic documents and run your real queries.
- Verify with explain() and revisit the model when query patterns change.
mongosh Examples
// One-to-few: embed addresses in the customer
db.customers.insertOne({
_id: 1,
name: "Asha",
addresses: [
{ type: "home", city: "Pune" },
{ type: "work", city: "Mumbai" }
]
})
// One-to-many with growth: reference the parent from each order
db.orders.insertMany([
{ _id: 101, customerId: 1, total: 250, placedAt: new Date() },
{ _id: 102, customerId: 1, total: 90, placedAt: new Date() }
])
db.orders.createIndex({ customerId: 1 })
// Read the parent and its orders
db.customers.findOne({ _id: 1 })
db.orders.find({ customerId: 1 })
// Or join in an aggregation pipeline
db.customers.aggregate([
{ $match: { _id: 1 } },
{ $lookup: { from: "orders", localField: "_id", foreignField: "customerId", as: "orders" } }
]) Edge Cases & Pitfalls
Unbounded embedded arrays
Comments, events, or logs inside a parent can grow past the document size limit and slow every write to that document.
Duplicated data goes stale
If you copy data (like a product name) into many documents, plan how you will keep it consistent.
$lookup is not free
Joins at read time add cost. If you do them on every request, consider embedding instead.
Do not copy a relational model blindly
Normalizing everything into many collections gives up one of MongoDB's main benefits.
Cheat Sheet
| Topic | Detail |
|---|---|
| Embedding | Store related data as a subdocument or array inside one document |
| Referencing | Store another document's _id and look it up separately or with $lookup |
| One-to-one | Usually embed, for example a user profile inside a user |
| One-to-few | Embed an array, for example a few addresses per customer |
| One-to-many | Reference from the many side, or embed when bounded |
| One-to-squillions | Put the parent _id in each child document, for example log entries |
| Many-to-many | Arrays of references on one or both sides |
| Atomicity | Single-document writes are atomic, a strong reason to embed |
| 16 MiB limit | Documents cannot exceed this, so avoid unbounded embedded arrays |
Key Takeaways
Embed data that is accessed together and is bounded in size. Reference data that grows without limit, is shared by many parents, or is updated independently. Start from your queries, not from entity diagrams.
Frequently Asked Questions
When should I embed documents?
When the data is accessed together, the relationship is one-to-one or one-to-few, and the embedded data does not grow without bound.
When should I use references?
When the related data is large, grows indefinitely, is shared across many parents, or is updated independently of the parent.
How do I model a one-to-many relationship?
If the many side is small and bounded, embed an array. If it can grow large, store the parent _id in each child document and index it.
Does MongoDB support joins?
Yes. The $lookup aggregation stage joins collections, but good modeling often avoids needing joins for common reads.
Is it okay to duplicate data?
Sometimes. Duplicating rarely changing values can speed up reads, but you must accept the extra work of keeping copies in sync.
Do I need to define a schema first?
No. The schema is flexible, though you can add validation rules to a collection once your model settles.
Next: MongoDB Aggregation Expressions
Continue the MongoDB learning path.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
8 people found this page helpful
