0
0
MongoDBquery~5 mins

Embedded documents (nested objects) in MongoDB

Choose your learning style9 modes available
Introduction

Embedded documents let you store related information inside a single record. This keeps data organized and easy to find.

When you want to keep related details together, like a person's address inside their profile.
When you want to avoid multiple database lookups by storing connected data in one place.
When the nested data is small and always used with the main document.
When you want to model real-world objects that naturally contain other objects, like a blog post with comments.
When you want to update related data in one operation.
Syntax
MongoDB
{
  field1: value1,
  nestedField: {
    subField1: value2,
    subField2: value3
  }
}
Embedded documents are like mini-records inside a main record.
You can nest documents as deep as you need, but keep it simple for easy use.
Examples
This example shows a person with an embedded address document.
MongoDB
{
  name: "Alice",
  address: {
    street: "123 Main St",
    city: "Springfield"
  }
}
Here, product details are stored inside the main product document.
MongoDB
{
  product: "Book",
  details: {
    author: "John Doe",
    pages: 250
  }
}
This example uses an array of embedded documents to list order items.
MongoDB
{
  orderId: 101,
  items: [
    { name: "Pen", qty: 3 },
    { name: "Notebook", qty: 1 }
  ]
}
Sample Program

This inserts a user with embedded contact info, then retrieves and prints it.

MongoDB
db.users.insertOne({
  name: "Bob",
  contact: {
    email: "bob@example.com",
    phone: "555-1234"
  }
});

// Find the user and show the embedded contact info
const user = db.users.findOne({ name: "Bob" });
printjson(user);
OutputSuccess
Important Notes

Embedded documents help keep related data together, making queries simpler.

Too much nesting can make documents large and slow to read or write.

Use embedded documents when the nested data is closely tied to the main document.

Summary

Embedded documents store related data inside a main document.

They make data easier to access and keep related info together.

Use them wisely to keep your database efficient and simple.