InterviewHubPRO
Section Overview
Q28

Question 28 of 60

Part 3: NoSQL & Document Databases (MongoDB, DynamoDB) (26 - 40)

47%
Databases & System Design•Part 3: NoSQL & Document Databases (MongoDB, DynamoDB) (26 - 40)

MongoDB: Embedding vs Referencing:

In Simple Words:

  • Embed: For 1-to-few relationships where child data is always retrieved with parent (Order Items in an Order).
  • Reference: For 1-to-many or many-to-many relationships where data updates frequently or approaches 16MB document size limit.
javascript
// 1. Embedding (Atomic single document update):
db.orders.updateOne(
  { _id: "ord_1" },
  { $push: { items: { name: "Keyboard", price: 79 } } }
);

// 2. Referencing (Separate collections):
db.orders.aggregate([
  { $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } }
]);