0
0
MongoDBquery~5 mins

One-to-one embedding pattern in MongoDB

Choose your learning style9 modes available
Introduction

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

When two pieces of information always belong together, like a user and their profile.
When you want to avoid extra steps to get related data.
When the related data is small and won't grow much over time.
When you rarely need to access the related data separately.
When you want to keep your database queries simple and quick.
Syntax
MongoDB
db.collection.insertOne({
  mainField1: value1,
  mainField2: value2,
  embeddedField: {
    subField1: valueA,
    subField2: valueB
  }
})
The embeddedField holds the related data inside the main document.
Use this pattern when the embedded data is small and tightly connected.
Examples
This example stores a user's profile inside the user document.
MongoDB
db.users.insertOne({
  name: "Alice",
  email: "alice@example.com",
  profile: {
    age: 30,
    city: "New York"
  }
})
The shipping address is embedded inside the order document.
MongoDB
db.orders.insertOne({
  orderId: 12345,
  product: "Book",
  shippingAddress: {
    street: "123 Main St",
    city: "Boston",
    zip: "02101"
  }
})
Sample Program

This inserts an employee with embedded contact information, then retrieves it.

MongoDB
db.employees.insertOne({
  employeeId: 1,
  name: "John Doe",
  contactInfo: {
    phone: "555-1234",
    email: "john.doe@example.com"
  }
})

db.employees.find({ employeeId: 1 })
OutputSuccess
Important Notes

Embedding keeps related data together, which can speed up reading.

Don't embed if the embedded data grows too large or changes often.

Use embedding for data that is always accessed together.

Summary

One-to-one embedding stores related data inside one document.

It is best for small, tightly connected data.

This pattern simplifies queries and improves read speed.