This pattern helps store related data together in one place. It makes reading data faster and simpler.
One-to-many embedding pattern in MongoDB
Introduction
Syntax
MongoDB
db.collection.insertOne({
mainField1: value1,
mainField2: value2,
relatedItems: [
{ subField1: valueA, subField2: valueB },
{ subField1: valueC, subField2: valueD }
]
})The related items are stored as an array inside the main document.
This keeps related data together, avoiding separate queries.
Examples
MongoDB
db.posts.insertOne({
title: "My First Post",
author: "Alice",
comments: [
{ user: "Bob", message: "Nice post!" },
{ user: "Carol", message: "Thanks for sharing." }
]
})MongoDB
db.orders.insertOne({
orderId: 12345,
customer: "John",
items: [
{ product: "Book", quantity: 2 },
{ product: "Pen", quantity: 5 }
]
})Sample Program
This inserts a library document with a list of books inside it. Then it finds and prints the library with its books.
MongoDB
db.library.insertOne({
name: "City Library",
address: "123 Main St",
books: [
{ title: "1984", author: "George Orwell" },
{ title: "To Kill a Mockingbird", author: "Harper Lee" }
]
})
// Query to find the library and its books
const library = db.library.findOne({ name: "City Library" })
printjson(library)Important Notes
Embedding is good for data that is mostly read together.
If the embedded array grows too large, it can slow down queries and updates.
For very large or growing related data, consider referencing instead of embedding.
Summary
One-to-many embedding stores related data inside a main document.
It makes reading related data faster and simpler.
Best for small to medium related data that is read together.
Practice
1. What is the main advantage of using the
one-to-many embedding pattern in MongoDB?easy
Solution
Step 1: Understand embedding in MongoDB
Embedding means storing related data inside the main document instead of separate collections.Step 2: Identify the advantage of embedding
This approach makes reading related data faster and simpler because all data is in one place.Final Answer:
It stores related data inside the main document for faster reads. -> Option DQuick Check:
Embedding = faster reads [OK]
Hint: Embedding means related data inside main document for quick access [OK]
Common Mistakes:
- Confusing embedding with referencing (separate collections)
- Thinking embedding requires joins
- Assuming embedding duplicates data
2. Which of the following is the correct way to embed multiple comments inside a blog post document in MongoDB?
easy
Solution
Step 1: Check the structure for embedding multiple comments
Embedding many comments requires an array of objects inside the main document.Step 2: Identify the correct JSON syntax
{ _id: 1, title: 'Post', comments: [{ user: 'Alice', text: 'Nice!' }, { user: 'Bob', text: 'Great!' }] } correctly uses an array of comment objects inside thecommentsfield.Final Answer:
{ _id: 1, title: 'Post', comments: [{ user: 'Alice', text: 'Nice!' }, { user: 'Bob', text: 'Great!' }] } -> Option CQuick Check:
Array of objects = correct embedding [OK]
Hint: Embed many items as an array of objects inside the document [OK]
Common Mistakes:
- Using multiple objects without array brackets
- Storing comments as a string instead of objects
- Incorrect JSON syntax with misplaced commas or braces
3. Given the following document in a
What will be the result of the query
posts collection:{ _id: 1, title: 'Hello', comments: [{ user: 'Alice', text: 'Hi' }, { user: 'Bob', text: 'Hello' }] }What will be the result of the query
db.posts.find({ _id: 1 }, { 'comments.user': 1, _id: 0 })?medium
Solution
Step 1: Understand the projection in the query
The query projects only thecomments.userfield and excludes_id.Step 2: Determine the output structure
It returns thecommentsarray with only theuserfields inside each comment object.Final Answer:
{ comments: [{ user: 'Alice' }, { user: 'Bob' }] } -> Option AQuick Check:
Projection of comments.user = array of user objects [OK]
Hint: Projection with dot notation returns array of objects with that field [OK]
Common Mistakes:
- Expecting full comment objects instead of only user fields
- Including _id when excluded in projection
- Getting array of strings instead of objects
4. You have this document:
Which update query correctly adds a new product
{ _id: 1, name: 'Store', products: [{ name: 'Pen', price: 1.5 }, { name: 'Pencil', price: 1.0 }] }Which update query correctly adds a new product
{ name: 'Eraser', price: 0.5 } to the products array?medium
Solution
Step 1: Identify the correct operator to add an object to an array
The$pushoperator adds an element to an array field.Step 2: Check the value being pushed
db.stores.updateOne({ _id: 1 }, { $push: { products: { name: 'Eraser', price: 0.5 } } }) pushes the correct object{ name: 'Eraser', price: 0.5 }into theproductsarray.Final Answer:
db.stores.updateOne({ _id: 1 }, { $push: { products: { name: 'Eraser', price: 0.5 } } }) -> Option AQuick Check:
$push with object adds to array [OK]
Hint: Use $push with full object to add to embedded array [OK]
Common Mistakes:
- Using $set replaces whole array instead of adding
- Using $addToSet with a string instead of object
- Pushing array instead of object inside array
5. You want to store a user's orders in a single document using one-to-many embedding. Each order has an
orderId, date, and a list of items. Which schema design is best to handle up to 100 orders per user efficiently?hard
Solution
Step 1: Understand embedding for one-to-many with moderate size
Embedding up to 100 orders inside a user document is reasonable for fast reads.Step 2: Check schema design for correct embedding
{ _id: userId, name: 'User', orders: [{ orderId, date, items: [{ productId, qty }] }] } embeds an array of order objects, each with its own items array, which fits the one-to-many embedding pattern well.Final Answer:
{ _id: userId, name: 'User', orders: [{ orderId, date, items: [{ productId, qty }] }] } -> Option BQuick Check:
Embed array of orders with nested items for one-to-many [OK]
Hint: Embed arrays of objects for moderate related data size [OK]
Common Mistakes:
- Using object instead of array for multiple orders
- Separating orders into another collection unnecessarily
- Storing only order IDs without details inside user
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
