0
0
MongoDBquery~5 mins

Insert with nested documents in MongoDB

Choose your learning style9 modes available
Introduction

We use nested documents to store related information inside one record. This keeps data organized and easy to find.

When you want to save a person's contact info along with their address in one place.
When storing a product with multiple features or specifications inside it.
When keeping a blog post with comments inside the same document.
When saving an order with a list of items bought together.
When grouping related settings or preferences inside a user profile.
Syntax
MongoDB
db.collection.insertOne({
  key1: value1,
  key2: {
    nestedKey1: nestedValue1,
    nestedKey2: nestedValue2
  }
})
Nested documents are like mini-records inside a main record.
Use curly braces { } to create nested documents.
Examples
Insert a user with a nested contact document holding email and phone.
MongoDB
db.users.insertOne({
  name: "Alice",
  contact: {
    email: "alice@example.com",
    phone: "123-456-7890"
  }
})
Insert a product with nested specs describing CPU and RAM.
MongoDB
db.products.insertOne({
  name: "Laptop",
  specs: {
    cpu: "Intel i7",
    ram: "16GB"
  }
})
Insert an order with an array of nested item documents.
MongoDB
db.orders.insertOne({
  orderId: 101,
  items: [
    { product: "Pen", quantity: 3 },
    { product: "Notebook", quantity: 1 }
  ]
})
Sample Program

This inserts a student record with a nested address document containing street, city, and zip.

MongoDB
db.students.insertOne({
  name: "John Doe",
  age: 20,
  address: {
    street: "123 Main St",
    city: "Anytown",
    zip: "12345"
  }
})
OutputSuccess
Important Notes

Nested documents help keep related data together in one place.

You can nest documents as deep as you need, but keep it readable.

Arrays can hold multiple nested documents for lists of items.

Summary

Use nested documents to group related data inside one record.

Use curly braces { } to create nested documents.

Insert nested documents with insertOne or insertMany commands.