Introduction
This pattern helps store related information together in one place. It makes reading data faster and simpler.
This pattern helps store related information together in one place. It makes reading data faster and simpler.
db.collection.insertOne({
mainField1: value1,
mainField2: value2,
embeddedField: {
subField1: valueA,
subField2: valueB
}
})db.users.insertOne({
name: "Alice",
email: "alice@example.com",
profile: {
age: 30,
city: "New York"
}
})db.orders.insertOne({
orderId: 12345,
product: "Book",
shippingAddress: {
street: "123 Main St",
city: "Boston",
zip: "02101"
}
})This inserts an employee with embedded contact information, then retrieves it.
db.employees.insertOne({
employeeId: 1,
name: "John Doe",
contactInfo: {
phone: "555-1234",
email: "john.doe@example.com"
}
})
db.employees.find({ employeeId: 1 })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.
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.
one-to-one embedding pattern in MongoDB?profile document inside a user document in MongoDB?{ _id: 1, name: 'Bob', address: { street: 'Main St', city: 'LA' } }, what will be the result of the query db.users.findOne({ _id: 1 })?{ _id: 2, name: 'Carol', profile: { age: 25, city: 'Chicago' } }. Which update command correctly changes the city to 'Boston' using one-to-one embedding?Pass the test and this pattern moves unknown