Bird
Raised Fist0
MongoDBquery~20 mins

One-to-many embedding pattern in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MongoDB One-to-Many Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Find all authors with their books embedded
Given a MongoDB collection authors where each document embeds an array of books, what is the output of this query?

db.authors.find({}, {name: 1, books: 1, _id: 0})
MongoDB
db.authors.find({}, {name: 1, books: 1, _id: 0})
A[ { _id: ObjectId("...") }, { _id: ObjectId("...") } ]
B[ { name: "Alice" }, { name: "Bob" } ]
C[ { books: [{title: "Book A1"}, {title: "Book A2"}] }, { books: [{title: "Book B1"}] } ]
D[ { name: "Alice", books: [{title: "Book A1"}, {title: "Book A2"}] }, { name: "Bob", books: [{title: "Book B1"}] } ]
Attempts:
2 left
💡 Hint
Projection includes name and books, excludes _id.
🧠 Conceptual
intermediate
1:30remaining
Why embed one-to-many data in MongoDB?
Which is the main reason to use embedding for one-to-many relationships in MongoDB?
ATo allow multiple collections to share the same document
BTo enforce strict relational integrity like foreign keys
CTo keep related data together for faster reads and simpler queries
DTo reduce document size below 1 KB
Attempts:
2 left
💡 Hint
Think about how embedding affects data retrieval speed.
📝 Syntax
advanced
2:00remaining
Correct syntax to add a book to an author's embedded books array
Which MongoDB update command correctly adds a new book to the embedded books array of the author named "Alice"?
MongoDB
New book to add: { title: "Book A3", year: 2024 }
Adb.authors.updateOne({name: "Alice"}, {$addToSet: {books: {title: "Book A3", year: 2024}}})
Bdb.authors.updateOne({name: "Alice"}, {$push: {books: {title: "Book A3", year: 2024}}})
Cdb.authors.updateOne({name: "Alice"}, {$set: {books: {title: "Book A3", year: 2024}}})
Ddb.authors.updateOne({name: "Alice"}, {$push: {books: [{title: "Book A3", year: 2024}]}})
Attempts:
2 left
💡 Hint
Use the operator that adds an element to an array.
🔧 Debug
advanced
2:30remaining
Why does this embedded update fail?
Given this update command:

db.authors.updateOne({name: "Alice"}, {$push: {books: {title: "Book A4"}}})

It fails with an error about document size. What is the most likely cause?
AThe embedded books array is too large and exceeds MongoDB's 16MB document size limit
BThe $push operator requires an array, not an object
CThe query filter {name: "Alice"} does not match any document
DThe update command is missing the <code>multi: true</code> option
Attempts:
2 left
💡 Hint
Think about MongoDB document size limits when embedding many items.
❓ optimization
expert
3:00remaining
Best approach to model a one-to-many relationship with thousands of related items
You have an author with thousands of books. Embedding all books in one document causes performance and size issues. What is the best MongoDB design pattern to handle this?
AUse referencing: store author in one collection and books in another with author_id field
BSplit the books array into multiple embedded arrays inside the author document
CEmbed all books anyway and increase MongoDB document size limit
DStore all books as a single large string field inside the author document
Attempts:
2 left
💡 Hint
Consider MongoDB document size limits and query performance.

Practice

(1/5)
1. What is the main advantage of using the one-to-many embedding pattern in MongoDB?
easy
A. It separates related data into different collections for better normalization.
B. It duplicates data across multiple documents to improve write speed.
C. It requires complex joins to retrieve related data.
D. It stores related data inside the main document for faster reads.

Solution

  1. Step 1: Understand embedding in MongoDB

    Embedding means storing related data inside the main document instead of separate collections.
  2. Step 2: Identify the advantage of embedding

    This approach makes reading related data faster and simpler because all data is in one place.
  3. Final Answer:

    It stores related data inside the main document for faster reads. -> Option D
  4. Quick 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
A. { _id: 1, title: 'Post', comments: 'Alice: Nice!, Bob: Great!' }
B. { _id: 1, title: 'Post', comments: { user: 'Alice', text: 'Nice!' }, { user: 'Bob', text: 'Great!' } }
C. { _id: 1, title: 'Post', comments: [{ user: 'Alice', text: 'Nice!' }, { user: 'Bob', text: 'Great!' }] }
D. { _id: 1, title: 'Post', comments: [{ user: 'Alice' }, user: 'Bob', text: 'Great!' ] }

Solution

  1. Step 1: Check the structure for embedding multiple comments

    Embedding many comments requires an array of objects inside the main document.
  2. 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 the comments field.
  3. Final Answer:

    { _id: 1, title: 'Post', comments: [{ user: 'Alice', text: 'Nice!' }, { user: 'Bob', text: 'Great!' }] } -> Option C
  4. Quick 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 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
A. { comments: [{ user: 'Alice' }, { user: 'Bob' }] }
B. { comments: [{ text: 'Hi' }, { text: 'Hello' }] }
C. { _id: 1, comments: [{ user: 'Alice' }, { user: 'Bob' }] }
D. { comments: ['Alice', 'Bob'] }

Solution

  1. Step 1: Understand the projection in the query

    The query projects only the comments.user field and excludes _id.
  2. Step 2: Determine the output structure

    It returns the comments array with only the user fields inside each comment object.
  3. Final Answer:

    { comments: [{ user: 'Alice' }, { user: 'Bob' }] } -> Option A
  4. Quick 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:
{ _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
A. db.stores.updateOne({ _id: 1 }, { $push: { products: { name: 'Eraser', price: 0.5 } } })
B. db.stores.updateOne({ _id: 1 }, { $addToSet: { products: 'Eraser' } })
C. db.stores.updateOne({ _id: 1 }, { $set: { products: { name: 'Eraser', price: 0.5 } } })
D. db.stores.updateOne({ _id: 1 }, { $push: { products: ['Eraser', 0.5] } })

Solution

  1. Step 1: Identify the correct operator to add an object to an array

    The $push operator adds an element to an array field.
  2. 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 the products array.
  3. Final Answer:

    db.stores.updateOne({ _id: 1 }, { $push: { products: { name: 'Eraser', price: 0.5 } } }) -> Option A
  4. Quick 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
A. Separate orders collection with userId reference for each order
B. { _id: userId, name: 'User', orders: [{ orderId, date, items: [{ productId, qty }] }] }
C. { _id: userId, name: 'User', orderIds: [orderId1, orderId2], orders: [] }
D. { _id: userId, name: 'User', orders: { orderId, date, items: [{ productId, qty }] } }

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    { _id: userId, name: 'User', orders: [{ orderId, date, items: [{ productId, qty }] }] } -> Option B
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard