Introduction
We use nested documents to store related information inside one record. This keeps data organized and easy to find.
Jump into concepts and practice - no test required
We use nested documents to store related information inside one record. This keeps data organized and easy to find.
db.collection.insertOne({
key1: value1,
key2: {
nestedKey1: nestedValue1,
nestedKey2: nestedValue2
}
})db.users.insertOne({
name: "Alice",
contact: {
email: "alice@example.com",
phone: "123-456-7890"
}
})db.products.insertOne({
name: "Laptop",
specs: {
cpu: "Intel i7",
ram: "16GB"
}
})db.orders.insertOne({
orderId: 101,
items: [
{ product: "Pen", quantity: 3 },
{ product: "Notebook", quantity: 1 }
]
})This inserts a student record with a nested address document containing street, city, and zip.
db.students.insertOne({
name: "John Doe",
age: 20,
address: {
street: "123 Main St",
city: "Anytown",
zip: "12345"
}
})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.
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.
insertOne in MongoDB?db.users.insertOne({name: "Bob", contact: {email: "bob@example.com", phone: "123-456"}})db.products.insertOne({name: "Pen", details: [color: "blue", price: 1.5]})insertMany. Which command correctly inserts two users with nested addresses?