MongoDB and the Document Model unit, 1:1 relationship example

In MongoDB, a 1:1 relationship means one document is linked to exactly one other document. Since MongoDB is document-based, you usually embed the related data inside the same document instead of using separate tables like in SQL.

Example: Suppose you have a User and a Profile where each user has exactly one profile.

You can embed the profile directly inside the user document:

{
“_id”: 1,
“name”: “Alice”,
“email”: “alice@example.com”,
“profile”: {
“age”: 30,
“address”: “123 Main St”,
“phone”: “555-1234”
}
}

This is simple and efficient for 1:1 relationships because the related data is always loaded together.

Alternatively, if the profile is large or accessed separately, you can store it in a separate collection and reference it by ID:

// User document
{
“_id”: 1,
“name”: “Alice”,
“email”: “alice@example.com”,
“profile_id”: 101
}

// Profile document
{
“_id”: 101,
“age”: 30,
“address”: “123 Main St”,
“phone”: “555-1234”
}

You’d then query the profile separately using the profile_id.

2 Likes