Update MongoDB Arrays

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to update MongoDB arrays using various techniques, including pushing new elements, pulling array items, updating array elements, adding to array sets, and removing duplicates. The lab covers practical examples and step-by-step instructions to help you master the management of arrays in your MongoDB databases. You will explore how to dynamically modify document data and maintain the integrity of your array-based structures.

The lab starts by demonstrating how to add new elements to arrays using the $push operator. It then covers the $pull operator, which allows you to remove specific items from arrays. Additionally, you will learn how to update individual array elements, add elements to array sets, and remove duplicates from arrays. These techniques will equip you with the necessary skills to effectively work with arrays and embedded documents in your MongoDB applications.


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/AggregationOperationsGroup(["`Aggregation Operations`"]) mongodb/BasicOperationsGroup -.-> mongodb/insert_document("`Insert Document`") mongodb/BasicOperationsGroup -.-> mongodb/update_document("`Update Document`") mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/DataTypesGroup -.-> mongodb/manage_array_elements("`Manage Array Elements`") mongodb/AggregationOperationsGroup -.-> mongodb/aggregate_group_totals("`Aggregate Group Totals`") subgraph Lab Skills mongodb/insert_document -.-> lab-422095{{"`Update MongoDB Arrays`"}} mongodb/update_document -.-> lab-422095{{"`Update MongoDB Arrays`"}} mongodb/find_documents -.-> lab-422095{{"`Update MongoDB Arrays`"}} mongodb/manage_array_elements -.-> lab-422095{{"`Update MongoDB Arrays`"}} mongodb/aggregate_group_totals -.-> lab-422095{{"`Update MongoDB Arrays`"}} end

Push New Elements

In this step, you'll learn how to add new elements to arrays in MongoDB using the $push operator. Arrays in MongoDB are powerful and flexible, allowing you to dynamically modify your document's data.

First, let's start the MongoDB shell and create a database for our lab:

mongosh
use arraylab

Now, let's create a collection called students with an initial document that has an array of courses:

db.students.insertOne({
    name: "Alice Johnson",
    courses: ["Mathematics", "Computer Science"]
})

To add a new course to Alice's list of courses, we'll use the $push operator:

db.students.updateOne(
    { name: "Alice Johnson" },
    { $push: { courses: "Data Structures" } }
)

Let's verify the update by finding Alice's document:

db.students.find({ name: "Alice Johnson" })

Example output:

[
  {
    _id: ObjectId("..."),
    name: 'Alice Johnson',
    courses: [ 'Mathematics', 'Computer Science', 'Data Structures' ]
  }
]

The $push operator allows you to add elements to an array. In this example, we added "Data Structures" to Alice's list of courses.

You can also push multiple elements at once using $push with the $each modifier:

db.students.updateOne(
    { name: "Alice Johnson" },
    { $push: { courses: { $each: ["Physics", "Chemistry"] } } }
)

This adds both "Physics" and "Chemistry" to Alice's courses array.

Pull Array Items

In this step, you'll learn how to remove elements from arrays in MongoDB using the $pull operator. Building on the previous step, we'll continue working with our students collection in the arraylab database.

First, ensure you're in the MongoDB shell and using the correct database:

mongosh
use arraylab

Let's verify our existing student document:

db.students.find({ name: "Alice Johnson" })

To remove a specific item from an array, we'll use the $pull operator. Let's remove the "Physics" course from Alice's courses:

db.students.updateOne(
    { name: "Alice Johnson" },
    { $pull: { courses: "Physics" } }
)

Now, let's check the updated document:

db.students.find({ name: "Alice Johnson" })

Example output:

[
  {
    _id: ObjectId("..."),
    name: 'Alice Johnson',
    courses: [ 'Mathematics', 'Computer Science', 'Data Structures', 'Chemistry' ]
  }
]

You can also remove multiple specific items using $pull with an array of values:

db.students.updateOne(
    { name: "Alice Johnson" },
    { $pullAll: { courses: ["Mathematics", "Chemistry"] } }
)

The $pullAll operator removes all specified values from the array in a single operation.

Let's verify the final state of Alice's courses:

db.students.find({ name: "Alice Johnson" })

Example output:

[
  {
    _id: ObjectId("..."),
    name: 'Alice Johnson',
    courses: [ 'Computer Science', 'Data Structures' ]
  }
]

Update Array Elements

In this step, you'll learn how to update specific elements within an array in MongoDB using positional and array filtering operators.

First, ensure you're in the MongoDB shell and using the correct database:

mongosh
use arraylab

Let's create a more complex document with an array of student courses:

db.students.insertOne({
    name: "Bob Smith",
    courses: [
        { name: "Mathematics", grade: "B" },
        { name: "Computer Science", grade: "A" },
        { name: "Physics", grade: "C" }
    ]
})

To update a specific element in an array, we'll use the positional $ operator. Let's update the grade for Computer Science:

db.students.updateOne(
    { name: "Bob Smith", "courses.name": "Computer Science" },
    { $set: { "courses.$.grade": "A+" } }
)

Let's verify the update:

db.students.find({ name: "Bob Smith" })

Example output:

[
  {
    _id: ObjectId("..."),
    name: 'Bob Smith',
    courses: [
      { name: 'Mathematics', grade: 'B' },
      { name: 'Computer Science', grade: 'A+' },
      { name: 'Physics', grade: 'C' }
    ]
  }
]

We can also use the $[] operator to update all elements in an array. Let's add a semester to all courses:

db.students.updateOne(
    { name: "Bob Smith" },
    { $set: { "courses.$[].semester": "Fall 2023" } }
)

Let's check the final document:

db.students.find({ name: "Bob Smith" })

Example output:

[
  {
    _id: ObjectId("..."),
    name: 'Bob Smith',
    courses: [
      { name: 'Mathematics', grade: 'B', semester: 'Fall 2023' },
      { name: 'Computer Science', grade: 'A+', semester: 'Fall 2023' },
      { name: 'Physics', grade: 'C', semester: 'Fall 2023' }
    ]
  }
]

Add To Array Sets

In this step, you'll learn how to add unique elements to an array using the $addToSet operator in MongoDB, which prevents duplicate entries.

First, ensure you're in the MongoDB shell and using the correct database:

mongosh
use arraylab

Let's create a new document with a student's skills array:

db.students.insertOne({
    name: "Emma Wilson",
    skills: ["Python", "JavaScript"]
})

The $addToSet operator adds an element to an array only if it doesn't already exist:

db.students.updateOne(
    { name: "Emma Wilson" },
    { $addToSet: { skills: "Python" } }
)

Let's verify the document:

db.students.find({ name: "Emma Wilson" })

Example output:

[
  {
    _id: ObjectId("..."),
    name: 'Emma Wilson',
    skills: ['Python', 'JavaScript']
  }
]

Notice that "Python" wasn't added again because it already existed.

You can also add multiple unique elements at once using $addToSet with $each:

db.students.updateOne(
    { name: "Emma Wilson" },
    { $addToSet: {
        skills: {
            $each: ["React", "Node.js", "Python", "TypeScript"]
        }
    } }
)

Let's check the final document:

db.students.find({ name: "Emma Wilson" })

Example output:

[
  {
    _id: ObjectId("..."),
    name: 'Emma Wilson',
    skills: ['Python', 'JavaScript', 'React', 'Node.js', 'TypeScript']
  }
]

Note how "Python" was not duplicated, while the new skills were added.

Remove Duplicates

In this step, you'll learn how to remove duplicate elements from an array in MongoDB using aggregation and update operations.

First, ensure you're in the MongoDB shell and using the correct database:

mongosh
use arraylab

Let's create a document with duplicate skills:

db.students.insertOne({
    name: "Michael Chen",
    skills: ["Python", "JavaScript", "Python", "React", "JavaScript", "Node.js"]
})

To remove duplicates, we'll use the $addToSet operator, which automatically eliminates duplicates:

db.students.updateOne(
    { name: "Michael Chen" },
    { $set: { skills: { $setUnique: "$skills" } } }
)

Alternatively, we can use an aggregation pipeline to remove duplicates:

db.students.aggregate([
    { $match: { name: "Michael Chen" } },
    { $project: {
        name: 1,
        skills: { $setUnique: "$skills" }
    } },
    { $merge: { into: "students", on: "name", whenMatched: "replace" } }
])

Let's verify the document:

db.students.find({ name: "Michael Chen" })

Example output:

[
  {
    _id: ObjectId("..."),
    name: 'Michael Chen',
    skills: ['Python', 'JavaScript', 'React', 'Node.js']
  }
]

We can also demonstrate removing duplicates while maintaining the original order of first appearance:

db.students.updateOne(
    { name: "Michael Chen" },
    { $set: {
        skills: Array.from(new Set(db.students.findOne({ name: "Michael Chen" }).skills))
    } }
)

Let's do a final check:

db.students.find({ name: "Michael Chen" })

Summary

In this lab, you learned how to update MongoDB arrays using various operators. First, you learned to add new elements to arrays using the $push operator, including pushing multiple elements at once. Then, you explored how to remove specific items from arrays using the $pull operator. Additionally, you discovered how to update individual elements within an array and how to add elements to an array set to avoid duplicates. These techniques provide a solid foundation for dynamically managing array data in your MongoDB applications.

Other MongoDB Tutorials you may like