Introduction
In this lab, you will learn how to manipulate arrays within MongoDB documents. You will practice adding, removing, and updating array elements using MongoDB's powerful update operators. The lab provides step-by-step instructions and practical examples to help you master array management in your MongoDB databases.
You will begin by adding elements to an array using the $push operator. Next, you will learn to remove elements using the $pull and $pullAll operators. You will also explore how to modify specific elements within an array and how to use $addToSet to ensure that an array only contains unique elements. Finally, you will learn how to remove existing duplicates from an array using an aggregation pipeline.
Adding Elements to an Array with $push
In this step, you will learn how to add new elements to an array in a MongoDB document using the $push operator. This operator appends a specified value to an array.
First, open the MongoDB shell to interact with your database. All database operations in this lab will be performed inside this shell.
mongosh
Once inside the shell, switch to the arraylab database. This database was created for you during the setup process.
use arraylab
The setup script also created a students collection with one document. Let's find this document to see its current state.
db.students.findOne({ name: "Alice Johnson" })
You should see the following output, which shows Alice is enrolled in two courses:
{
_id: ObjectId('...'),
name: 'Alice Johnson',
courses: [ 'Mathematics', 'Computer Science' ]
}
Now, let's add a new course, "Data Structures", to Alice's courses array using the $push operator.
db.students.updateOne(
{ name: "Alice Johnson" },
{ $push: { courses: "Data Structures" } }
)
The updateOne method finds a document matching the filter { name: "Alice Johnson" } and applies the update { $push: { courses: "Data Structures" } }. The $push operator appends the new course to the courses array.
You can also add multiple elements at once by combining $push with the $each modifier. Let's add "Physics" and "Chemistry" to the array.
db.students.updateOne(
{ name: "Alice Johnson" },
{ $push: { courses: { $each: ["Physics", "Chemistry"] } } }
)
To confirm that all new courses have been added, run the findOne command again.
db.students.findOne({ name: "Alice Johnson" })
The updated document now contains all five courses:
{
_id: ObjectId('...'),
name: 'Alice Johnson',
courses: [
'Mathematics',
'Computer Science',
'Data Structures',
'Physics',
'Chemistry'
]
}
Removing Elements from an Array
In this step, you will learn how to remove elements from an array using the $pull and $pullAll operators. $pull removes all instances of a specified value, while $pullAll removes all instances of multiple specified values.
You should still be in the mongosh shell from the previous step. Let's start by removing the "Physics" course from Alice's list using the $pull operator.
db.students.updateOne(
{ name: "Alice Johnson" },
{ $pull: { courses: "Physics" } }
)
This command finds the document for "Alice Johnson" and removes the string "Physics" from her courses array.
Next, let's remove multiple courses at once. The $pullAll operator is perfect for this. We will remove "Mathematics" and "Chemistry".
db.students.updateOne(
{ name: "Alice Johnson" },
{ $pullAll: { courses: ["Mathematics", "Chemistry"] } }
)
Now, let's verify the final state of the document to see which courses remain.
db.students.findOne({ name: "Alice Johnson" })
The output shows that "Physics", "Mathematics", and "Chemistry" have been removed, leaving only two courses.
{
_id: ObjectId('...'),
name: 'Alice Johnson',
courses: [ 'Computer Science', 'Data Structures' ]
}
Updating Specific Elements in an Array
In this step, you will learn how to modify specific elements within an array. This is useful when your array contains objects and you need to update a field in one of those objects.
First, let's insert a new student document. This document's courses array will contain objects, each with a name and a grade.
db.students.insertOne({
name: "Bob Smith",
courses: [
{ name: "Mathematics", grade: "B" },
{ name: "Computer Science", grade: "A" },
{ name: "Physics", grade: "C" }
]
})
Suppose we want to change Bob's grade in "Computer Science" from "A" to "A+". We can use the positional $ operator. This operator acts as a placeholder for the first element that matches the query condition.
db.students.updateOne(
{ name: "Bob Smith", "courses.name": "Computer Science" },
{ $set: { "courses.$.grade": "A+" } }
)
In this command, the query { "courses.name": "Computer Science" } identifies the correct array element. The update { $set: { "courses.$.grade": "A+" } } then uses $ to refer to that element and update its grade field.
Let's verify the change.
db.students.findOne({ name: "Bob Smith" })
The output will show the updated grade:
{
_id: ObjectId('...'),
name: 'Bob Smith',
courses: [
{ name: 'Mathematics', grade: 'B' },
{ name: 'Computer Science', grade: 'A+' },
{ name: 'Physics', grade: 'C' }
]
}
You can also update all elements in an array at once using the all positional operator $[ ]. Let's add a semester field to all of Bob's courses.
db.students.updateOne(
{ name: "Bob Smith" },
{ $set: { "courses.$[].semester": "Fall 2023" } }
)
Check the final document to see the result.
db.students.findOne({ name: "Bob Smith" })
All course objects in the array now have the semester field.
{
_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' }
]
}
Ensuring Unique Elements with $addToSet
In this step, you will learn to use the $addToSet operator. This operator adds an element to an array only if it does not already exist in the array, thereby preventing duplicate entries.
First, let's add a new student with an array of skills.
db.students.insertOne({
name: "Emma Wilson",
skills: ["Python", "JavaScript"]
})
Now, let's try to add "Python" again using $addToSet. Since "Python" is already in the array, this operation will not change the document.
db.students.updateOne(
{ name: "Emma Wilson" },
{ $addToSet: { skills: "Python" } }
)
Let's check the document to confirm.
db.students.findOne({ name: "Emma Wilson" })
You will see that the skills array has not changed, because "Python" was already present.
{
_id: ObjectId('...'),
name: 'Emma Wilson',
skills: [ 'Python', 'JavaScript' ]
}
Like $push, $addToSet can be combined with the $each modifier to add multiple values. It will add only the values that are not already in the array.
db.students.updateOne(
{ name: "Emma Wilson" },
{ $addToSet: {
skills: {
$each: ["React", "Node.js", "Python", "TypeScript"]
}
} }
)
Let's check the final document.
db.students.findOne({ name: "Emma Wilson" })
The new, unique skills have been added, while the duplicate "Python" was ignored.
{
_id: ObjectId('...'),
name: 'Emma Wilson',
skills: [ 'Python', 'JavaScript', 'React', 'Node.js', 'TypeScript' ]
}
Removing Existing Duplicates from an Array
While $addToSet prevents adding new duplicates, sometimes you might have a document where an array already contains duplicate values. In this step, you will learn how to remove existing duplicates using an aggregation pipeline.
First, let's insert a document with a skills array that contains duplicates.
db.students.insertOne({
name: "Michael Chen",
skills: ["Python", "JavaScript", "Python", "React", "JavaScript", "Node.js"]
})
To remove these duplicates, we can use an aggregation pipeline with the $merge stage. This pipeline will read the document, create a new array with unique elements, and then update the original document.
First, we need to create an index on the name field to ensure the $merge operation works correctly:
db.students.createIndex({ name: 1 }, { unique: true })
Now, run the following aggregation command:
db.students.aggregate([
{ $match: { name: "Michael Chen" } },
{ $project: {
name: 1,
skills: { $setUnion: "$skills" }
} },
{ $merge: { into: "students", on: "name", whenMatched: "replace" } }
])
Let's break down this pipeline:
$match: This stage filters the documents to process only the one for "Michael Chen".$project: This stage reshapes the document. We keep thenamefield and replace theskillsarray with the output of$setUnion: "$skills". The$setUnionoperator takes an array and returns a new array containing only the unique elements.$merge: This stage writes the results of the pipeline back into thestudentscollection. It finds the document to update based on thenamefield (on: "name") and replaces the entire document with the new one from the pipeline (whenMatched: "replace"). The index we created ensures efficient matching and updating.
Now, let's verify that the duplicates have been removed.
db.students.findOne({ name: "Michael Chen" })
The output will show the skills array with only unique elements. The order of elements may vary.
{
_id: ObjectId('...'),
name: 'Michael Chen',
skills: [ 'JavaScript', 'Node.js', 'Python', 'React' ]
}
Summary
In this lab, you have learned several essential techniques for managing arrays in MongoDB. You practiced adding elements with $push, removing them with $pull and $pullAll, and updating specific elements using the positional $ operator. You also explored how to maintain unique elements in an array with $addToSet and how to clean up existing duplicates using an aggregation pipeline with $setUnion and $merge. These skills are fundamental for building dynamic and robust applications with MongoDB.

