MongoDB References Practice Questions with Solutions

Introduction

MongoDB provides two common ways to represent relationships between data: embedded documents and references. References store a relationship between documents by keeping the _id of another document. This approach is useful when related data is large, shared by multiple documents, or needs to be managed independently. In this chapter, you will practice creating references, storing ObjectIds, finding related documents, and understanding how references are used in MongoDB. MongoDB References practice questions with solutions to help you understand the concepts.

Q1. Create a Student Document

Problem Statement:
Create a student document that will later be referenced by another document.

MongoDB Query:

db.students.insertOne({
  name: "Rahul",
  age: 16,
  course: "Python"
})

Expected Output:

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

Explanation:
MongoDB automatically generates an _id for Rahul. This _id can be stored in another document as a reference.


Q2. Create a Course Document

Problem Statement:
Create a course document that contains the course name and duration.

MongoDB Query:

db.courses.insertOne({
  name: "Python Full Course",
  duration: "6 Months"
})

Expected Output:

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

Explanation:
The generated _id of this course can be referenced by other documents.


Q3. Store a Course Reference in a Student Document

Problem Statement:
Suppose the course document has the following _id:

ObjectId("650000000000000000000001")

Store this course ID as a reference inside a student document.

MongoDB Query:

db.students.insertOne({
  name: "Priya",
  age: 17,
  courseId: ObjectId("650000000000000000000001")
})

Expected Output:

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

Explanation:
The courseId field stores the _id of a document from the courses collection.

This creates a relationship like:

Student
   |
   └── courseId → Course

Q4. Find a Student Using the Referenced Course ID

Problem Statement:
Find students who are enrolled in the course whose _id is:

ObjectId("650000000000000000000001")

MongoDB Query:

db.students.find({
  courseId: ObjectId("650000000000000000000001")
})

Expected Output:

{
  name: "Priya",
  age: 17,
  courseId: ObjectId("650000000000000000000001")
}

Explanation:
MongoDB compares the stored ObjectId with the referenced course’s _id.


Q5. Create an Employee with a Department Reference

Problem Statement:
Create a department document and then store its _id as a reference in an employee document.

MongoDB Query:

db.departments.insertOne({
  name: "IT",
  floor: 3
})

Suppose MongoDB returns:

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

Now create the employee:

db.employees.insertOne({
  name: "Neha",
  salary: 45000,
  departmentId: ObjectId("650000000000000000000002")
})

Expected Output:

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

Explanation:
The employee does not store the complete department document. It stores the department’s _id.


Q6. Find the Referenced Department

Problem Statement:
Find the department referenced by an employee’s departmentId.

Suppose:

departmentId: ObjectId("650000000000000000000002")

MongoDB Query:

db.departments.findOne({
  _id: ObjectId("650000000000000000000002")
})

Expected Output:

{
  _id: ObjectId("650000000000000000000002"),
  name: "IT",
  floor: 3
}

Explanation:
MongoDB does not automatically follow a reference when using find() or findOne().

You query the referenced collection separately using the stored _id.


Q7. Create an Order with a Customer Reference

Problem Statement:
Suppose a customer has the _id:

ObjectId("650000000000000000000003")

Create an order that references this customer.

MongoDB Query:

db.orders.insertOne({
  orderNumber: "ORD1001",
  amount: 2500,
  customerId: ObjectId("650000000000000000000003")
})

Expected Output:

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

Explanation:
The customerId field stores the customer’s _id.

The relationship is:

Order
  |
  └── customerId → Customer

Q8. Find All Orders Belonging to a Customer

Problem Statement:
Find all orders for the customer whose _id is:

ObjectId("650000000000000000000003")

MongoDB Query:

db.orders.find({
  customerId: ObjectId("650000000000000000000003")
})

Expected Output:

{
  orderNumber: "ORD1001",
  amount: 2500,
  customerId: ObjectId("650000000000000000000003")
}

{
  orderNumber: "ORD1002",
  amount: 1800,
  customerId: ObjectId("650000000000000000000003")
}

Explanation:
Multiple orders can store the same customer’s _id. This represents a one-to-many relationship.


Q9. Use $lookup to Get Referenced Course Details

Problem Statement:
Find students and combine their referenced course information from the courses collection.

Suppose the student contains:

courseId: ObjectId("650000000000000000000001")

MongoDB Query:

db.students.aggregate([
  {
    $lookup: {
      from: "courses",
      localField: "courseId",
      foreignField: "_id",
      as: "courseDetails"
    }
  }
])

Expected Output:

{
  name: "Priya",
  age: 17,
  courseId: ObjectId("650000000000000000000001"),
  courseDetails: [
    {
      _id: ObjectId("650000000000000000000001"),
      name: "Python Full Course",
      duration: "6 Months"
    }
  ]
}

Explanation:
$lookup performs a join-like operation between collections.

Here:

students.courseId
       ↓
courses._id

The matching course is placed inside the courseDetails array.


Q10. Use $lookup and $unwind to Show Course Details Directly

Problem Statement:
Find students and their referenced course, but display the course as an object instead of an array.

MongoDB Query:

db.students.aggregate([
  {
    $lookup: {
      from: "courses",
      localField: "courseId",
      foreignField: "_id",
      as: "courseDetails"
    }
  },
  {
    $unwind: "$courseDetails"
  }
])

Expected Output:

{
  name: "Priya",
  age: 17,
  courseId: ObjectId("650000000000000000000001"),
  courseDetails: {
    _id: ObjectId("650000000000000000000001"),
    name: "Python Full Course",
    duration: "6 Months"
  }
}

Explanation:
$lookup creates an array called courseDetails.

$unwind converts the single matching array element into a normal embedded object.

This is useful when working with referenced data in aggregation pipelines.

Key Takeaways

  • A reference stores the _id of another MongoDB document.
  • References are commonly used to represent relationships between collections.
  • ObjectId is frequently used as the value of a reference field.
  • MongoDB does not automatically fetch referenced documents with find().
  • You can query the referenced collection separately using its _id.
  • One customer can be referenced by many orders, creating a one-to-many relationship.
  • $lookup can combine related documents from different collections.
  • $unwind can convert a single-element lookup array into an object.
  • References are useful when related data needs to be stored and managed independently.
  • Choosing between embedding and referencing depends on how the data is related and accessed.

FAQs

1. What is a reference in MongoDB?

A reference is a field that stores the _id of a document from another collection.

For example:

{
  name: "Priya",
  courseId: ObjectId("650000000000000000000001")
}

Here, courseId references a document in the courses collection.

2. Why are references used in MongoDB?

References are useful when related information is large, shared by multiple documents, or needs to be maintained independently.

For example, many orders can reference the same customer.

3. Does MongoDB automatically follow references?

No. MongoDB does not automatically retrieve the referenced document when you run a normal find() query.

You can query the other collection separately or use $lookup in an aggregation pipeline.

4. What is the difference between embedded documents and references?

An embedded document stores related information directly inside the document:

{
  name: "Rahul",
  address: {
    city: "Delhi"
  }
}

A reference stores another document’s ID:

{
  name: "Rahul",
  addressId: ObjectId("...")
}

5. Can MongoDB references use ObjectId?

Yes. ObjectId is commonly used for references because MongoDB automatically uses an ObjectId as the _id when one is not provided.

6. How do you retrieve referenced documents in MongoDB?

You can use the aggregation $lookup stage:

db.students.aggregate([
  {
    $lookup: {
      from: "courses",
      localField: "courseId",
      foreignField: "_id",
      as: "courseDetails"
    }
  }
])

7. What is $lookup used for in MongoDB references?

$lookup is used to combine documents from another collection based on matching fields. It is commonly used when working with referenced documents.

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

Scroll to Top