MongoDB One-to-Many Relationships Practice Questions with Solutions

Introduction

A one-to-many relationship in MongoDB means that one document is connected to multiple related documents. For example, one customer can have many orders, one teacher can have many students, or one department can have many employees. MongoDB supports one-to-many relationships using embedded documents, arrays, and references. In this chapter, you will practice creating, querying, updating, and connecting related documents using practical MongoDB commands. MongoDB One-to-Many Relationships Practice Questions with Solutions to help you understand the concepts.

Q1. Create a Customer with Multiple Embedded Addresses

Problem Statement

Create a customer document that contains multiple addresses inside an addresses array.

MongoDB Command / Query

db.customers.insertOne({
  name: "Rahul",
  email: "rahul@example.com",
  addresses: [
    {
      type: "Home",
      city: "Delhi",
      pincode: 110075
    },
    {
      type: "Office",
      city: "Noida",
      pincode: 201301
    }
  ]
})

Expected Output

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

One customer contains multiple address documents, creating a one-to-many relationship inside the same document.


Q2. Find Customers Having an Address in Delhi

Problem Statement

Find customers whose addresses array contains an address from Delhi.

MongoDB Command / Query

db.customers.find({
  "addresses.city": "Delhi"
})

Expected Output

{
  _id: ObjectId("..."),
  name: "Rahul",
  email: "rahul@example.com",
  addresses: [
    {
      type: "Home",
      city: "Delhi",
      pincode: 110075
    },
    {
      type: "Office",
      city: "Noida",
      pincode: 201301
    }
  ]
}

MongoDB’s dot notation allows you to search fields inside objects stored in an array.


Q3. Create One Teacher with Multiple Students

Problem Statement

Create a teacher document containing multiple student names in a students array.

MongoDB Command / Query

db.teachers.insertOne({
  name: "Priya Sharma",
  subject: "Python",
  students: [
    "Aman",
    "Neha",
    "Rohit",
    "Simran"
  ]
})

Expected Output

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

One teacher is connected to multiple students through the students array.


Q4. Add Another Student to the Teacher

Problem Statement

Add a new student named Karan to Priya Sharma’s student list.

MongoDB Command / Query

db.teachers.updateOne(
  { name: "Priya Sharma" },
  { $push: { students: "Karan" } }
)

Expected Output

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

The $push operator adds a new value to the students array.


Q5. Create Orders Using a Reference

Problem Statement

Create one customer and multiple orders. Store the customer’s _id as customerId in each order.

MongoDB Command / Query

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

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

db.orders.insertMany([
  {
    customerId: customer._id,
    product: "Laptop",
    amount: 55000
  },
  {
    customerId: customer._id,
    product: "Mouse",
    amount: 800
  },
  {
    customerId: customer._id,
    product: "Keyboard",
    amount: 1500
  }
])

Expected Output

{
  acknowledged: true,
  insertedIds: {
    "0": ObjectId("..."),
    "1": ObjectId("..."),
    "2": ObjectId("...")
  }
}

One customer is connected to multiple order documents through the same customerId.


Q6. Find All Orders of a Customer

Problem Statement

Find all orders that belong to Aman.

MongoDB Command / Query

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

db.orders.find({
  customerId: customer._id
})

Expected Output

{
  _id: ObjectId("..."),
  customerId: ObjectId("..."),
  product: "Laptop",
  amount: 55000
}
{
  _id: ObjectId("..."),
  customerId: ObjectId("..."),
  product: "Mouse",
  amount: 800
}
{
  _id: ObjectId("..."),
  customerId: ObjectId("..."),
  product: "Keyboard",
  amount: 1500
}

The same customerId connects multiple order documents to one customer.


Q7. Find Customers Who Have Multiple Orders

Problem Statement

Find customer IDs that have more than one order.

MongoDB Command / Query

db.orders.aggregate([
  {
    $group: {
      _id: "$customerId",
      orderCount: { $sum: 1 }
    }
  },
  {
    $match: {
      orderCount: { $gt: 1 }
    }
  }
])

Expected Output

{
  _id: ObjectId("..."),
  orderCount: 3
}

$group groups orders by customerId, and $sum counts how many orders each customer has.


Q8. Combine Customers and Their Orders Using $lookup

Problem Statement

Display each customer together with all of their orders.

MongoDB Command / Query

db.customers.aggregate([
  {
    $lookup: {
      from: "orders",
      localField: "_id",
      foreignField: "customerId",
      as: "orders"
    }
  }
])

Expected Output

{
  _id: ObjectId("..."),
  name: "Aman",
  email: "aman@example.com",
  orders: [
    {
      _id: ObjectId("..."),
      customerId: ObjectId("..."),
      product: "Laptop",
      amount: 55000
    },
    {
      _id: ObjectId("..."),
      customerId: ObjectId("..."),
      product: "Mouse",
      amount: 800
    },
    {
      _id: ObjectId("..."),
      customerId: ObjectId("..."),
      product: "Keyboard",
      amount: 1500
    }
  ]
}

$lookup joins the customer document with all matching order documents.


Q9. Find Customers Having an Order Above ₹10,000

Problem Statement

Find customers whose related orders contain at least one order with an amount greater than 10000.

MongoDB Command / Query

db.customers.aggregate([
  {
    $lookup: {
      from: "orders",
      localField: "_id",
      foreignField: "customerId",
      as: "orders"
    }
  },
  {
    $match: {
      "orders.amount": { $gt: 10000 }
    }
  }
])

Expected Output

{
  _id: ObjectId("..."),
  name: "Aman",
  email: "aman@example.com",
  orders: [
    {
      _id: ObjectId("..."),
      customerId: ObjectId("..."),
      product: "Laptop",
      amount: 55000
    },
    {
      _id: ObjectId("..."),
      customerId: ObjectId("..."),
      product: "Mouse",
      amount: 800
    }
  ]
}

The $match stage checks whether the joined orders array contains an order with an amount greater than 10000.


Q10. Remove One Item from an Embedded One-to-Many Array

Problem Statement

Remove Karan from Priya Sharma’s student list.

MongoDB Command / Query

db.teachers.updateOne(
  { name: "Priya Sharma" },
  { $pull: { students: "Karan" } }
)

Expected Output

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

The $pull operator removes matching values from an array.

Key Takeaways

  • A one-to-many relationship connects one document with multiple related documents.
  • MongoDB can represent one-to-many relationships using arrays.
  • Related data can also be stored in separate collections using references.
  • $push adds an item to an array.
  • $pull removes matching items from an array.
  • Dot notation can query fields inside objects stored in arrays.
  • $lookup can combine one parent document with multiple related documents.
  • $group can be used to count related documents.
  • Embedding is useful when related data is small and normally accessed together.
  • References are useful when the related documents are large, independently managed, or need to be queried separately.

FAQs

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

A one-to-many relationship means one document is associated with multiple related documents. For example, one customer can have many orders.

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

You can create it using an array of embedded documents or by storing the parent document’s _id as a reference in multiple documents in another collection.

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

A customer and orders are a common example. One customer can place many orders, while each order belongs to one customer.

4. When should one-to-many data be embedded?

Embedding can be a good choice when the related data is relatively small and is usually accessed together with the parent document.

5. When should one-to-many data use references?

References are useful when there can be many related documents, the related documents are large, or they need to be managed and queried independently.

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

$lookup combines documents from another collection based on matching fields. It can return multiple related documents in an array.

7. What is the difference between $push and $pull?

$push adds a value to an array, while $pull removes matching values from an array.

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

Scroll to Top