0
0
MongoDBquery~5 mins

One-to-many embedding pattern in MongoDB

Choose your learning style9 modes available
Introduction

This pattern helps store related data together in one place. It makes reading data faster and simpler.

When you have a main item with many related details, like a blog post with many comments.
When the related data is mostly read together with the main data.
When the number of related items is not too large to slow down the main document.
When you want to keep data organized and easy to access in one document.
Syntax
MongoDB
db.collection.insertOne({
  mainField1: value1,
  mainField2: value2,
  relatedItems: [
    { subField1: valueA, subField2: valueB },
    { subField1: valueC, subField2: valueD }
  ]
})

The related items are stored as an array inside the main document.

This keeps related data together, avoiding separate queries.

Examples
This example stores a blog post with two comments inside the same document.
MongoDB
db.posts.insertOne({
  title: "My First Post",
  author: "Alice",
  comments: [
    { user: "Bob", message: "Nice post!" },
    { user: "Carol", message: "Thanks for sharing." }
  ]
})
This example stores an order with multiple items embedded inside it.
MongoDB
db.orders.insertOne({
  orderId: 12345,
  customer: "John",
  items: [
    { product: "Book", quantity: 2 },
    { product: "Pen", quantity: 5 }
  ]
})
Sample Program

This inserts a library document with a list of books inside it. Then it finds and prints the library with its books.

MongoDB
db.library.insertOne({
  name: "City Library",
  address: "123 Main St",
  books: [
    { title: "1984", author: "George Orwell" },
    { title: "To Kill a Mockingbird", author: "Harper Lee" }
  ]
})

// Query to find the library and its books
const library = db.library.findOne({ name: "City Library" })
printjson(library)
OutputSuccess
Important Notes

Embedding is good for data that is mostly read together.

If the embedded array grows too large, it can slow down queries and updates.

For very large or growing related data, consider referencing instead of embedding.

Summary

One-to-many embedding stores related data inside a main document.

It makes reading related data faster and simpler.

Best for small to medium related data that is read together.