One to One Relationship in MongoDB: Explanation and Example
one to one relationship in MongoDB means each document in one collection is linked to exactly one document in another collection. This is usually done by storing a reference (like an ID) from one document to the other, ensuring a unique pairing between them.How It Works
Imagine you have two sets of things, like people and their passports. Each person has exactly one passport, and each passport belongs to exactly one person. In MongoDB, a one to one relationship works the same way by linking one document in a collection to one document in another collection.
This link is usually made by storing the unique ID of one document inside the other. For example, a person document might store the ID of their passport document. This way, you can easily find the matching document without duplication.
Unlike traditional databases, MongoDB lets you either embed the related document inside the main document or keep them separate and link by IDs. The choice depends on how often you need to access or update the related data.
Example
This example shows two collections: users and profiles. Each user has one profile linked by the profile_id field.
db.users.insertOne({ _id: 1, name: "Alice", profile_id: 101 })
db.profiles.insertOne({ _id: 101, age: 30, city: "New York" })
// Query to find user with profile details
const user = db.users.findOne({ _id: 1 });
const profile = db.profiles.findOne({ _id: user.profile_id });
printjson({ user, profile });When to Use
Use a one to one relationship in MongoDB when you want to keep related data separate but linked, especially if the related data is large or changes independently. For example, storing user login info separately from user profile details helps keep data organized and secure.
It is also useful when you want to avoid duplicating data but still need quick access to related information. This pattern fits well for things like user and address, employee and badge, or product and warranty details.
Key Points
- A one to one relationship links exactly one document in one collection to one document in another.
- It is implemented by storing a reference ID from one document to the other.
- You can embed the related document or keep it separate depending on your needs.
- Useful for separating concerns, reducing duplication, and organizing data clearly.