Manage MongoDB Embedded Docs

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to effectively manage MongoDB embedded documents. The lab covers a range of techniques, including creating nested documents, updating nested fields, removing nested elements, querying nested data, and validating document structure. These skills are essential for working with complex, hierarchical data in MongoDB, enabling you to build robust and efficient applications. The step-by-step instructions provide a comprehensive guide to mastering the management of embedded documents in your MongoDB projects.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/DataTypesGroup(["`Data Types`"]) mongodb(("`MongoDB`")) -.-> mongodb/ArrayandEmbeddedDocumentsGroup(["`Array and Embedded Documents`"]) mongodb/BasicOperationsGroup -.-> mongodb/update_document("`Update Document`") mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("`Query with Conditions`") mongodb/DataTypesGroup -.-> mongodb/manage_array_elements("`Manage Array Elements`") mongodb/ArrayandEmbeddedDocumentsGroup -.-> mongodb/create_embedded_documents("`Create Embedded Documents`") mongodb/ArrayandEmbeddedDocumentsGroup -.-> mongodb/query_embedded_documents("`Query Embedded Documents`") subgraph Lab Skills mongodb/update_document -.-> lab-422088{{"`Manage MongoDB Embedded Docs`"}} mongodb/find_documents -.-> lab-422088{{"`Manage MongoDB Embedded Docs`"}} mongodb/query_with_conditions -.-> lab-422088{{"`Manage MongoDB Embedded Docs`"}} mongodb/manage_array_elements -.-> lab-422088{{"`Manage MongoDB Embedded Docs`"}} mongodb/create_embedded_documents -.-> lab-422088{{"`Manage MongoDB Embedded Docs`"}} mongodb/query_embedded_documents -.-> lab-422088{{"`Manage MongoDB Embedded Docs`"}} end

Create Nested Documents

In this step, you'll learn how to create nested documents in MongoDB, which allows you to store complex, hierarchical data within a single document. Nested documents are powerful for representing relationships and structured information.

First, let's start the MongoDB shell:

mongosh

Now, let's create a database for our example:

use bookstore

We'll create a collection called books with nested documents representing book details:

db.books.insertOne({
    title: "Advanced MongoDB",
    author: {
        name: "Jane Smith",
        contact: {
            email: "[email protected]",
            phone: "+1-555-123-4567"
        }
    },
    published: {
        year: 2023,
        publisher: "Tech Publications"
    },
    chapters: [
        { number: 1, title: "Introduction to Nested Documents" },
        { number: 2, title: "Advanced Document Structures" }
    ]
})

Let's break down this document:

  • The document has a main title field
  • author is a nested document with name and contact sub-documents
  • published is another nested document with publication details
  • chapters is an array of nested documents representing book chapters

To view the document we just created, use:

db.books.find()

Example output:

[
  {
    _id: ObjectId("..."),
    title: 'Advanced MongoDB',
    author: {
      name: 'Jane Smith',
      contact: {
        email: '[email protected]',
        phone: '+1-555-123-4567'
      }
    },
    published: {
      year: 2023,
      publisher: 'Tech Publications'
    },
    chapters: [
      { number: 1, title: 'Introduction to Nested Documents' },
      { number: 2, title: 'Advanced Document Structures' }
    ]
  }
]

Update Nested Fields

In this step, you'll learn how to update nested fields in MongoDB documents. Building on the previous step, we'll use the book document we created to demonstrate various update techniques for nested documents.

First, ensure you're in the MongoDB shell:

mongosh

Switch to the bookstore database:

use bookstore

Let's update the author's contact information using the $set operator:

db.books.updateOne(
    { title: "Advanced MongoDB" },
    { $set: {
        "author.contact.phone": "+1-888-999-0000",
        "author.contact.website": "www.janesmith.com"
    } }
)

The dot notation "author.contact.phone" allows us to precisely target nested fields. Let's verify the update:

db.books.find({ title: "Advanced MongoDB" })

Now, let's update a nested array. We'll add a new chapter to the chapters array:

db.books.updateOne(
    { title: "Advanced MongoDB" },
    { $push: {
        chapters: {
            number: 3,
            title: "MongoDB Advanced Techniques"
        }
    } }
)

The $push operator adds a new element to an array. Let's verify the update:

db.books.find({ title: "Advanced MongoDB" })

We can also update a specific nested array element using the positional $ operator. Let's update the first chapter:

db.books.updateOne(
    { title: "Advanced MongoDB", "chapters.number": 1 },
    { $set: {
        "chapters.$.title": "Introduction to Nested Documents (Revised)"
    } }
)

Example output will show the updated document with modified nested fields and added chapter.

Remove Nested Elements

In this step, you'll learn how to remove nested elements from MongoDB documents using various operators. We'll continue working with the book document from previous steps.

First, ensure you're in the MongoDB shell:

mongosh

Switch to the bookstore database:

use bookstore

Let's remove a specific field from the nested contact information using the $unset operator:

db.books.updateOne(
    { title: "Advanced MongoDB" },
    { $unset: { "author.contact.website": "" } }
)

The $unset operator removes the specified field completely. Let's verify the update:

db.books.find({ title: "Advanced MongoDB" })

Now, let's remove a specific element from the chapters array using the $pull operator:

db.books.updateOne(
    { title: "Advanced MongoDB" },
    { $pull: {
        chapters: { number: 3 }
    } }
)

The $pull operator removes all instances of a matching element from an array. Let's verify:

db.books.find({ title: "Advanced MongoDB" })

We can also remove the entire nested contact object:

db.books.updateOne(
    { title: "Advanced MongoDB" },
    { $unset: { "author.contact": "" } }
)

Example output will show the document with removed nested elements.

Query Nested Data

In this step, you'll learn how to query nested documents and arrays in MongoDB. We'll explore different techniques to filter and retrieve specific nested data.

First, let's reset our database with some sample data to demonstrate querying:

mongosh

Switch to the bookstore database:

use bookstore

Let's insert multiple books with nested structures:

db.books.insertMany([
    {
        title: "MongoDB Essentials",
        author: {
            name: "John Doe",
            experience: { years: 5, specialization: "Database Design" }
        },
        tags: ["beginner", "database", "nosql"],
        chapters: [
            { number: 1, title: "Introduction", pages: 25 },
            { number: 2, title: "Advanced Concepts", pages: 45 }
        ]
    },
    {
        title: "Advanced Database Techniques",
        author: {
            name: "Jane Smith",
            experience: { years: 8, specialization: "Distributed Systems" }
        },
        tags: ["advanced", "distributed", "nosql"],
        chapters: [
            { number: 1, title: "System Design", pages: 35 },
            { number: 2, title: "Performance Optimization", pages: 55 }
        ]
    }
])

Query a book by a nested field:

db.books.find({ "author.name": "John Doe" })

Query using dot notation for nested objects:

db.books.find({ "author.experience.specialization": "Database Design" })

Query using array contains:

db.books.find({ tags: "nosql" })

Query nested array elements:

db.books.find({ "chapters.pages": { $gt: 40 } })

The $gt operator means "greater than", so this finds books with chapters longer than 40 pages.

Complex query combining nested object and array conditions:

db.books.find({
    "author.experience.years": { $gte: 5 },
    tags: "advanced"
})

This finds books by authors with 5 or more years of experience and tagged as "advanced".

Validate Document Structure

In this step, you'll learn how to validate document structures in MongoDB using JSON Schema validation. This ensures that your documents maintain a consistent and predictable structure.

First, let's start the MongoDB shell:

mongosh

Switch to the bookstore database:

use bookstore

We'll create a new collection with a JSON Schema validator:

db.createCollection("courses", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: ["title", "instructor", "duration", "topics"],
         properties: {
            title: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            instructor: {
               bsonType: "object",
               required: ["name", "email"],
               properties: {
                  name: {
                     bsonType: "string",
                     description: "must be a string and is required"
                  },
                  email: {
                     bsonType: "string",
                     pattern: "^.+@.+$",
                     description: "must be a valid email address"
                  }
               }
            },
            duration: {
               bsonType: "int",
               minimum: 1,
               maximum: 100,
               description: "must be an integer between 1 and 100"
            },
            topics: {
               bsonType: "array",
               minItems: 1,
               items: {
                  bsonType: "string"
               },
               description: "must be an array of strings with at least one item"
            }
         }
      }
   }
})

Let's try inserting a valid document:

db.courses.insertOne({
   title: "MongoDB Advanced Techniques",
   instructor: {
      name: "Jane Smith",
      email: "[email protected]"
   },
   duration: 40,
   topics: ["Nested Documents", "Schema Validation"]
})

Now, let's try an invalid document that will be rejected:

db.courses.insertOne({
   title: "Invalid Course",
   instructor: {
      name: 123,  // Invalid: should be a string
      email: "invalid-email"  // Invalid email format
   },
   duration: 200,  // Out of range
   topics: []  // Empty topics array
})

This insertion will fail due to validation rules.

To see the validation rules for a collection:

db.getCollectionInfos({ name: "courses" })

Example output will show the JSON Schema validation configuration.

Summary

In this lab, you will learn how to manage MongoDB embedded documents. First, you will create nested documents, which allows you to store complex, hierarchical data within a single document. This is powerful for representing relationships and structured information. Next, you will update nested fields, remove nested elements, query nested data, and validate document structure. These techniques demonstrate the flexibility and power of MongoDB's document-oriented data model for working with complex, nested data structures.

Other MongoDB Tutorials you may like