Introduction
Embedded documents let you store related information inside a single record. This keeps data organized and easy to find.
Jump into concepts and practice - no test required
Embedded documents let you store related information inside a single record. This keeps data organized and easy to find.
{
field1: value1,
nestedField: {
subField1: value2,
subField2: value3
}
}{
name: "Alice",
address: {
street: "123 Main St",
city: "Springfield"
}
}{
product: "Book",
details: {
author: "John Doe",
pages: 250
}
}{
orderId: 101,
items: [
{ name: "Pen", qty: 3 },
{ name: "Notebook", qty: 1 }
]
}This inserts a user with embedded contact info, then retrieves and prints it.
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);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.
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.
{ name: 'Bob', contact: { email: 'bob@example.com', phone: '1234' } }, what will the query db.users.find({ 'contact.email': 'bob@example.com' }) return?db.users.updateOne({name: 'Eve'}, {address.city: 'LA'})