0% completed
Embedding data in documents is a powerful feature in MongoDB that allows related data to be stored within a single document. This denormalized approach can enhance performance by reducing the number of queries needed to retrieve related data. It is particularly useful for use cases where related data is frequently accessed together.
By embedding related data within a single document, MongoDB can efficiently retrieve and manipulate data, making it an effective strategy for many applications.
Use Case 1: Blog Posts with Comments
Use Case 2: Orders with Line Items
Let's consider an e-commerce application where we embed order line items within an order document.
Order Document:
Insert an order with embedded line items into the orders
collection:
db.orders.insertOne({ _id: 1, customer: "John Doe", orderDate: "2023-06-01", shippingAddress: { street: "123 Main St", city: "Anytown", zipcode: "12345" }, lineItems: [ { productId: "A1", productName: "Widget", quantity: 2, price: 25.00 }, { productId: "B2", productName: "Gadget", quantity: 1, price: 50.00 } ], totalAmount: 100.00 })
Example 1: Retrieve Order by Customer
db.orders.find({ customer: "John Doe" })
Example 2: Retrieve Specific Line Item
db.orders.find({ "lineItems.productId": "A1" })
Example: Update Quantity of a Line Item
db.orders.updateOne( { _id: 1, "lineItems.productId": "A1" }, { $set: { "lineItems.$.quantity": 3 } } )
Embedding data in documents is a powerful feature in MongoDB that simplifies queries, improves read performance, and ensures data locality. By embedding related data within a single document, you can efficiently retrieve and manage data. However, it's important to consider the document size limit and potential update overhead when designing your schema.
.....
.....
.....