MongoDB 1-to-1 Relationships Practice Questions with Solutions

Introduction

A one-to-one relationship in MongoDB means that one document is associated with exactly one related document. For example, one student can have one profile, or one employee can have one identity record. MongoDB can represent this relationship using embedded documents or references. In this chapter, you will practice creating, querying, updating, and connecting one-to-one related documents using practical MongoDB commands. MongoDB 1-to-1 Relationships practice questions with solutions to help you understand the concepts.

Q1. Create a Student with One Embedded Profile

Problem Statement

Create a students collection and insert a student with a single embedded profile containing email and phone number.

MongoDB Command / Query

db.students.insertOne({
  name: "Rahul",
  age: 16,
  profile: {
    email: "rahul@example.com",
    phone: "9876543210"
  }
})

Expected Output

{
  acknowledged: true,
  insertedId: ObjectId("...")
}

The profile is stored directly inside the student document, creating a one-to-one relationship.


Q2. Find a Student Using a Field from the One-to-One Profile

Problem Statement

Find the student whose profile email is rahul@example.com.

MongoDB Command / Query

db.students.find({
  "profile.email": "rahul@example.com"
})

Expected Output

{
  _id: ObjectId("..."),
  name: "Rahul",
  age: 16,
  profile: {
    email: "rahul@example.com",
    phone: "9876543210"
  }
}

The dot notation "profile.email" accesses a field inside the embedded profile.


Q3. Update the One-to-One Profile

Problem Statement

Change Rahul’s phone number from 9876543210 to 9999999999.

MongoDB Command / Query

db.students.updateOne(
  { name: "Rahul" },
  { $set: { "profile.phone": "9999999999" } }
)

Expected Output

{
  acknowledged: true,
  matchedCount: 1,
  modifiedCount: 1
}

Only the phone number inside the related profile is updated.


Q4. Create an Employee with One Embedded Address

Problem Statement

Create an employee document where each employee has one address containing city and pincode.

MongoDB Command / Query

db.employees.insertOne({
  name: "Priya",
  department: "IT",
  address: {
    city: "Delhi",
    pincode: 110075
  }
})

Expected Output

{
  acknowledged: true,
  insertedId: ObjectId("...")
}

The address is embedded inside the employee document.


Q5. Find Employees from a Specific City

Problem Statement

Find all employees whose one-to-one address has the city Delhi.

MongoDB Command / Query

db.employees.find({
  "address.city": "Delhi"
})

Expected Output

{
  _id: ObjectId("..."),
  name: "Priya",
  department: "IT",
  address: {
    city: "Delhi",
    pincode: 110075
  }
}

MongoDB uses dot notation to query fields inside the embedded one-to-one document.


Q6. Create a One-to-One Relationship Using References

Problem Statement

Create a users document and a separate userProfiles document. Store the profile document’s _id inside the user as profileId.

MongoDB Command / Query

db.users.insertOne({
  name: "Aman",
  email: "aman@example.com"
})

const user = db.users.findOne({ name: "Aman" })

db.userProfiles.insertOne({
  userId: user._id,
  phone: "8888888888",
  city: "Mumbai"
})

const profile = db.userProfiles.findOne({ userId: user._id })

db.users.updateOne(
  { _id: user._id },
  { $set: { profileId: profile._id } }
)

Expected Output

{
  acknowledged: true,
  insertedId: ObjectId("...")
}

The users document now contains a reference to its profile document.


Q7. Find the Profile Using the User Reference

Problem Statement

Find the profile associated with Aman using the user’s _id.

MongoDB Command / Query

const user = db.users.findOne({
  name: "Aman"
})

db.userProfiles.findOne({
  userId: user._id
})

Expected Output

{
  _id: ObjectId("..."),
  userId: ObjectId("..."),
  phone: "8888888888",
  city: "Mumbai"
}

MongoDB does not automatically follow references. You query the related collection using the stored reference.


Q8. Display User and Profile Together Using $lookup

Problem Statement

Combine the users and userProfiles collections to display the user’s name along with the related profile.

MongoDB Command / Query

db.users.aggregate([
  {
    $lookup: {
      from: "userProfiles",
      localField: "_id",
      foreignField: "userId",
      as: "profile"
    }
  }
])

Expected Output

{
  _id: ObjectId("..."),
  name: "Aman",
  email: "aman@example.com",
  profile: [
    {
      _id: ObjectId("..."),
      userId: ObjectId("..."),
      phone: "8888888888",
      city: "Mumbai"
    }
  ]
}

$lookup combines related documents from another collection. The result is returned as an array.


Q9. Convert the One-to-One $lookup Result into an Object

Problem Statement

Use $lookup and $unwind so that the profile appears as a single object instead of an array.

MongoDB Command / Query

db.users.aggregate([
  {
    $lookup: {
      from: "userProfiles",
      localField: "_id",
      foreignField: "userId",
      as: "profile"
    }
  },
  {
    $unwind: "$profile"
  }
])

Expected Output

{
  _id: ObjectId("..."),
  name: "Aman",
  email: "aman@example.com",
  profile: {
    _id: ObjectId("..."),
    userId: ObjectId("..."),
    phone: "8888888888",
    city: "Mumbai"
  }
}

$unwind converts the single-element profile array into an embedded-looking object in the aggregation result.


Q10. Create a One-to-One Customer and Passport Relationship

Problem Statement

Create a customer and a separate passport document. Store the customer’s _id inside the passport as customerId, then find the passport using the reference.

MongoDB Command / Query

db.customers.insertOne({
  name: "Neha",
  email: "neha@example.com"
})

const customer = db.customers.findOne({
  name: "Neha"
})

db.passports.insertOne({
  customerId: customer._id,
  passportNumber: "P1234567",
  country: "India"
})

db.passports.findOne({
  customerId: customer._id
})

Expected Output

{
  _id: ObjectId("..."),
  customerId: ObjectId("..."),
  passportNumber: "P1234567",
  country: "India"
}

Here, one customer is connected to one passport through the customerId reference.

Key Takeaways

  • A one-to-one relationship connects one document with one related document.
  • MongoDB can represent one-to-one relationships using embedded documents.
  • MongoDB can also represent them using references.
  • Embedded relationships can be queried using dot notation.
  • $lookup is useful when related documents are stored in separate collections.
  • $unwind can convert a single-element lookup array into an object.
  • MongoDB does not automatically dereference an ObjectId stored in another document.
  • Choose embedding when the related information naturally belongs to the main document and is usually accessed together.
  • Choose references when the related document needs to be managed independently.

FAQs

1. What is a one-to-one relationship in MongoDB?

A one-to-one relationship means that one document is associated with exactly one related document, such as one user having one profile.

2. How can you create a one-to-one relationship in MongoDB?

You can create it by embedding the related document inside the main document or by storing a reference such as an ObjectId in another document.

3. What is an example of a one-to-one relationship?

A user and user profile can have a one-to-one relationship when each user has exactly one profile.

4. Should one-to-one data be embedded or referenced?

It depends on how the data is used. Embedding is often convenient when the related information is small and normally accessed with the parent document. References are useful when the related data is managed separately.

5. Can MongoDB automatically follow a reference?

No. MongoDB does not automatically dereference ObjectId references during a normal find() operation. You can query the related collection or use $lookup.

6. What does $lookup do in a one-to-one relationship?

$lookup combines documents from another collection based on matching fields, such as a user’s _id and a profile’s userId.

7. Why is $unwind used with $lookup?

$lookup normally returns matching documents in an array. $unwind can turn a single matching array element into an individual object in the aggregation result.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top