Introduction
In MongoDB, related data can generally be stored using embedding or referencing. Embedding keeps related information inside the same document, while referencing stores related information in separate documents and connects them using an ID such as ObjectId. Choosing between these approaches depends on how the data is accessed, updated, and related. In this chapter, you will practice both approaches and learn when each one is useful. MongoDB Embedding vs Referencing Practice Questions with Solutions to help you understannd the concepts.
Q1. Embed an Address Inside a Customer Document
Problem Statement
Create a customer document with the customer’s address embedded inside the same document.
MongoDB Command / Query
db.customers.insertOne({
name: "Rahul",
email: "rahul@example.com",
address: {
city: "Delhi",
pincode: 110075
}
})
Expected Output
{
acknowledged: true,
insertedId: ObjectId("...")
}
Here, the address is stored directly inside the customer document. This is embedding.
Q2. Query an Embedded Document
Problem Statement
Find customers whose embedded address has the city Delhi.
MongoDB Command / Query
db.customers.find({
"address.city": "Delhi"
})
Expected Output
{
_id: ObjectId("..."),
name: "Rahul",
email: "rahul@example.com",
address: {
city: "Delhi",
pincode: 110075
}
}
Dot notation allows MongoDB to access fields inside an embedded document.
Q3. Create a Customer and Address Using References
Problem Statement
Create a customer and a separate address document. Store the customer’s _id in the address document.
MongoDB Command / Query
db.customers.insertOne({
name: "Priya",
email: "priya@example.com"
})
const customer = db.customers.findOne({
name: "Priya"
})
db.addresses.insertOne({
customerId: customer._id,
city: "Mumbai",
pincode: 400001
})
Expected Output
{
acknowledged: true,
insertedId: ObjectId("...")
}
The address is stored separately and connected to the customer through customerId. This is referencing.
Q4. Find Referenced Data
Problem Statement
Find Priya’s address using her customer _id.
MongoDB Command / Query
const customer = db.customers.findOne({
name: "Priya"
})
db.addresses.find({
customerId: customer._id
})
Expected Output
{
_id: ObjectId("..."),
customerId: ObjectId("..."),
city: "Mumbai",
pincode: 400001
}
With references, MongoDB stores the relationship using an ID. A normal find() does not automatically retrieve the referenced document.
Q5. Embed Multiple Items Inside an Order
Problem Statement
Create an order containing multiple products as embedded documents.
MongoDB Command / Query
db.orders.insertOne({
orderNumber: "ORD1001",
customer: "Aman",
items: [
{
product: "Laptop",
quantity: 1,
price: 55000
},
{
product: "Mouse",
quantity: 2,
price: 800
}
]
})
Expected Output
{
acknowledged: true,
insertedId: ObjectId("...")
}
The products are stored inside the order. This approach is convenient when order items are normally accessed together with the order.
Q6. Reference Products from an Order
Problem Statement
Create separate product documents and then create an order containing references to those products.
MongoDB Command / Query
db.products.insertMany([
{
name: "Laptop",
price: 55000
},
{
name: "Mouse",
price: 800
}
])
const laptop = db.products.findOne({
name: "Laptop"
})
const mouse = db.products.findOne({
name: "Mouse"
})
db.orders.insertOne({
orderNumber: "ORD1002",
customer: "Neha",
productIds: [
laptop._id,
mouse._id
]
})
Expected Output
{
acknowledged: true,
insertedId: ObjectId("...")
}
The order stores product IDs instead of complete product documents. This is a referencing approach.
Q7. Update Embedded Data
Problem Statement
Update Rahul’s embedded address pincode to 110076.
MongoDB Command / Query
db.customers.updateOne(
{ name: "Rahul" },
{
$set: {
"address.pincode": 110076
}
}
)
Expected Output
{
acknowledged: true,
matchedCount: 1,
modifiedCount: 1
}
With embedding, the related address can be updated directly inside the customer document.
Q8. Update Referenced Data
Problem Statement
Update Priya’s separately stored address pincode to 400002.
MongoDB Command / Query
const customer = db.customers.findOne({
name: "Priya"
})
db.addresses.updateOne(
{ customerId: customer._id },
{
$set: {
pincode: 400002
}
}
)
Expected Output
{
acknowledged: true,
matchedCount: 1,
modifiedCount: 1
}
When using references, the related document is updated in its own collection.
Q9. Combine Referenced Documents Using $lookup
Problem Statement
Display customers together with their separately stored addresses.
MongoDB Command / Query
db.customers.aggregate([
{
$lookup: {
from: "addresses",
localField: "_id",
foreignField: "customerId",
as: "address"
}
}
])
Expected Output
{
_id: ObjectId("..."),
name: "Priya",
email: "priya@example.com",
address: [
{
_id: ObjectId("..."),
customerId: ObjectId("..."),
city: "Mumbai",
pincode: 400002
}
]
}
$lookup allows MongoDB to combine related documents stored in separate collections.
Q10. Choose Embedding or Referencing for a Large Relationship
Problem Statement
A company has millions of orders. Each customer can have thousands of orders, and orders are queried and managed independently. Decide whether all orders should be embedded inside the customer document or stored separately using references.
MongoDB Command / Query
A reference-based design can look like this:
db.customers.insertOne({
name: "Rohit",
email: "rohit@example.com"
})
const customer = db.customers.findOne({
name: "Rohit"
})
db.orders.insertOne({
customerId: customer._id,
product: "Laptop",
amount: 55000
})
Expected Output
{
acknowledged: true,
insertedId: ObjectId("...")
}
Explanation
For a relationship with a very large number of related documents, storing every order inside the customer document can make the customer document unnecessarily large. Keeping orders in a separate collection allows orders to be managed and queried independently.
This demonstrates an important schema-design consideration: the size and growth of related data matter when choosing between embedding and referencing.
Key Takeaways
- Embedding in MongoDB stores related data directly inside the parent document.
- Referencing in MongoDB stores related data separately and connects documents using an ID.
- Embedded data can usually be retrieved with the parent document in a single query.
- Dot notation is useful for querying embedded fields.
- Referenced documents can be combined using
$lookup. - Embedding is often useful for small, closely related data that is accessed together.
- Referencing can be useful when related data is large, independently managed, or shared.
- The amount and growth of related data are important factors in schema design.
- There is no single embedding-or-referencing rule that applies to every MongoDB application.
- Good MongoDB schema design depends on how the application reads, writes, and uses the data.
FAQs
1. What is embedding in MongoDB?
Embedding means storing related data directly inside the parent document as an object or array.
2. What is referencing in MongoDB?
Referencing means storing related data in a separate document or collection and connecting it using a field such as an ObjectId.
3. Which is the difference between embedding and referencing?
With embedding, related data is stored inside the same document. With referencing, related data is stored separately and connected through a reference.
4. When should I use embedding in MongoDB?
Embedding can be useful when related data is relatively small, belongs closely to the parent document, and is normally accessed together with it.
5. When should I use referencing in MongoDB?
Referencing can be useful when related data is large, grows substantially, needs independent management, or is shared between multiple documents.
6. Does MongoDB automatically follow references?
No. MongoDB does not automatically dereference an ObjectId during a normal find() operation. You can query the related collection separately or use $lookup.
7. Is embedding always better than referencing?
Neither approach is universally better. The appropriate choice depends on the relationship, data size, growth, access patterns, and update requirements of the application.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
