Unlike traditional SQL databases that use joins to relate data across tables, MongoDB handles relationships differently. Since MongoDB stores data in flexible, schema-less JSON-like documents, relationships are usually managed using:
_id)Best when related data is frequently accessed together. In this method, one document contains another inside it.
{
_id: 1,
name: "John",
address: {
street: "123 Main St",
city: "New York"
}
}
Used when documents grow large or data is shared across collections. Reference another document using its _id.
// users collection
{
_id: 101,
name: "Alice"
}
// orders collection
{
_id: 5001,
userId: 101,
product: "Laptop"
}
To fetch related data, you can use the $lookup stage in aggregation (similar to JOIN):
db.orders.aggregate([
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "userDetails"
}
}
])
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!