Handle MongoDB Arrays

MongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to handle MongoDB arrays. Arrays are a fundamental data structure in MongoDB that allow you to store lists of values within a single document. You will explore various operations, including creating documents with array fields, adding and removing elements, updating values within arrays, and performing queries based on array content. These skills are essential for managing complex data structures effectively in MongoDB.

By the end of this lab, you will have a solid, practical understanding of how to work with MongoDB arrays, enabling you to build more sophisticated and flexible database schemas.

Create Documents with Array Fields

In this first step, you will connect to the MongoDB server and create a new document that includes an array field. Arrays are powerful because they let you store multiple related values, such as tags, comments, or courses, directly within a document.

First, open the MongoDB shell to start interacting with your database. You will perform all subsequent operations in this lab within the mongosh shell.

mongosh

Once inside the shell, you will see a prompt like test>. Let's switch to the arraylab database, which has been pre-configured for this lab.

use arraylab

The setup script has already created a students collection and inserted one document. Now, you will insert a new document for a student named "Alice Johnson". This document will have a courses field, which is an array of strings.

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

This command inserts a single document into the students collection. The courses field holds an array containing three string elements.

To confirm that the document was created successfully, you can use the find() method to retrieve all documents in the collection. The .pretty() method formats the output to be more readable.

db.students.find().pretty()

You should see two documents: the one for "Bob Smith" that was created during setup, and the "Alice Johnson" document you just added.

[
  {
    _id: ObjectId("..."),
    name: 'Bob Smith',
    grades: [ 95, 87, 92 ],
    activities: [ 'Chess Club', 'Debate Team' ]
  },
  {
    _id: ObjectId("..."),
    name: 'Alice Johnson',
    age: 22,
    courses: [ 'Mathematics', 'Computer Science', 'Physics' ]
  }
]

Add Elements to an Array

After creating arrays, a common task is to add new elements to them. In this step, you will learn how to use the $push operator to append elements to an existing array.

To add a single element to an array, use the $push operator in an update operation. Let's add a new course, "Data Science", to Alice Johnson's list of courses.

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

In this command, the first argument { name: "Alice Johnson" } is the filter that finds the document to update. The second argument { $push: { courses: "Data Science" } } specifies the update action. $push appends the value "Data Science" to the courses array.

Let's verify the change by finding Alice's document again.

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

The output shows the new course added to the array.

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

To add multiple elements at once, you can combine $push with the $each modifier. Let's add two new activities for Bob Smith.

db.students.updateOne(
    { name: "Bob Smith" },
    { $push: { activities: { $each: ["Robotics Club", "Swimming Team"] } } }
)

Here, $each tells $push to append every item from the provided list (["Robotics Club", "Swimming Team"]) to the activities array.

Verify this update as well:

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

The output confirms that both new activities have been added.

[
  {
    _id: ObjectId("..."),
    name: 'Bob Smith',
    grades: [ 95, 87, 92 ],
    activities: [ 'Chess Club', 'Debate Team', 'Robotics Club', 'Swimming Team' ]
  }
]

Remove Elements from an Array

Just as you can add elements, you also need to be able to remove them. MongoDB provides several operators for this purpose. In this step, you will learn to use $pull to remove elements by value and $pop to remove them by position.

To remove a specific element from an array based on its value, use the $pull operator. Let's remove "Physics" from Alice's list of courses.

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

This command finds the document for Alice and removes all occurrences of "Physics" from her courses array. Check the result:

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

The output shows that "Physics" is no longer in the array.

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

To remove multiple elements that match values in a list, you can use the $pullAll operator. Let's remove both "Chess Club" and "Debate Team" from Bob's activities.

db.students.updateOne(
    { name: "Bob Smith" },
    { $pullAll: { activities: ["Chess Club", "Debate Team"] } }
)

Verify the update for Bob's document:

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

The output confirms the removal of the specified activities.

[
  {
    _id: ObjectId("..."),
    name: 'Bob Smith',
    grades: [ 95, 87, 92 ],
    activities: [ 'Robotics Club', 'Swimming Team' ]
  }
]

If you need to remove an element from either the beginning or the end of an array, you can use the $pop operator. Use 1 to remove the last element and -1 to remove the first. Let's remove the last course from Alice's list.

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

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

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

The output shows that the last element, "Data Science", has been removed.

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

Update Elements in an Array

Updating existing elements within an array is another crucial operation. This step covers how to update array elements using positional operators.

To update a single, specific element in an array, you must first match the document and the element you want to change. Then, you can use the positional $ operator to perform the update. Let's change "Mathematics" to "Advanced Mathematics" in Alice's courses array.

db.students.updateOne(
    { name: "Alice Johnson", courses: "Mathematics" },
    { $set: { "courses.$": "Advanced Mathematics" } }
)

In this command, the filter { name: "Alice Johnson", courses: "Mathematics" } finds the document and identifies the position of the first occurrence of "Mathematics" in the array. The update { $set: { "courses.$": "Advanced Mathematics" } } uses courses.$ to refer to that matched element's position and sets its new value.

Verify the change:

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

The output shows the updated course name.

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

To update all elements in an array that match a condition, you can use the all-positional $[ ] operator. Let's increase all of Bob's grades by 5 points using the $inc (increment) operator.

db.students.updateOne(
    { name: "Bob Smith" },
    { $inc: { "grades.$[]": 5 } }
)

Here, grades.$[] applies the $inc operation to every element in the grades array.

Check Bob's new grades:

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

The output shows that each grade has been increased by 5.

[
  {
    _id: ObjectId("..."),
    name: 'Bob Smith',
    grades: [ 100, 92, 97 ],
    activities: [ 'Robotics Club', 'Swimming Team' ]
  }
]

Query Documents Based on Array Content

Querying is at the heart of any database. MongoDB offers a rich set of operators to query documents based on the contents of their arrays. In this final step, you will learn how to find documents by matching array elements and their properties.

To find all documents where an array contains a specific element, you can include that value in your query filter. Let's find all students enrolled in "Computer Science".

db.students.find({ courses: "Computer Science" }).pretty()

This query will return Alice's document, as her courses array contains "Computer Science".

To find documents where an array contains all of a specified set of elements, use the $all operator.

db.students.find({
    courses: { $all: ["Advanced Mathematics", "Computer Science"] }
}).pretty()

This will also return Alice's document because her courses array contains both of these values.

For more complex conditions on array elements, the $elemMatch operator is very useful. It allows you to specify multiple criteria that a single array element must meet. Let's find students who have at least one grade greater than 95.

db.students.find({
    grades: { $elemMatch: { $gt: 95 } }
}).pretty()

This query will return Bob's document, as he has grades that are now over 95. $gt stands for "greater than".

You can also query based on the number of elements in an array using the $size operator. Let's find students who are in exactly two activities.

db.students.find({
    activities: { $size: 2 }
}).pretty()

This will return Bob's document, as his activities array currently has two elements.

Finally, let's add one more student to practice a combined query.

db.students.insertOne({
    name: "Charlie Brown",
    courses: ["Art", "Music", "Literature"],
    grades: [88, 92, 85],
    activities: ["Painting Club"]
})

Now, find students who are taking either "Art" or "Music" (using the $in operator) AND have at least one grade greater than or equal to 90 (using $elemMatch with $gte).

db.students.find({
    courses: { $in: ["Art", "Music"] },
    grades: { $elemMatch: { $gte: 90 } }
}).pretty()

This query will return the document for "Charlie Brown", who meets both conditions.

Summary

In this lab, you have learned the fundamental techniques for handling arrays in MongoDB. You started by creating documents with array fields and then practiced adding elements using $push and $each. You explored removing elements by value with $pull and $pullAll, and by position with $pop. You also learned how to update specific array elements using the positional $ operator and all elements with the $[ ] operator. Finally, you practiced querying documents based on array content using operators like $all, $elemMatch, $size, and $in. These skills are crucial for building and managing applications with complex, nested data structures in MongoDB.