Lesson 21 of 50 – Arrays in MongoDB
42%

Arrays in MongoDB

An array in MongoDB is a field that stores multiple values inside a single document. Arrays are useful for storing information such as student subjects, product tags, skills, phone numbers, and hobbies.

1. What Is an Array?

An array is an ordered collection of values enclosed in square brackets []. An array can contain strings, numbers, documents, or other arrays.

Example
{
    name: "Rahul",
    age: 20,
    subjects: ["Java", "Python", "HTML"]
}

In this document, subjects is an array containing three values.

  • subjects[0] refers to "Java" conceptually.
  • subjects[1] refers to "Python" conceptually.
  • subjects[2] refers to "HTML" conceptually.

MongoDB queries use dot notation with numeric indexes to access array elements, such as "subjects.0".

2. Insert Documents Containing Arrays

We can store an array as a field when inserting a document.

Example
db.array_students.insertOne({
    name: "Rahul",
    age: 20,
    subjects: ["Java", "Python", "HTML"],
    marks: [75, 85, 90]
})

The document contains two arrays: subjects and marks.

Insert Multiple Students
db.array_students.insertMany([
    {
        name: "Priya",
        subjects: ["HTML", "CSS", "JavaScript"],
        skills: ["Design", "Programming"]
    },
    {
        name: "Aman",
        subjects: ["Python", "SQL"],
        skills: ["Problem Solving", "Programming"]
    }
])

Each student can have different values and different numbers of array elements.

3. Find Documents Using an Array Value

MongoDB can match a document when an array contains the specified value.

Example: Find Students Studying Python
db.array_students.find({
    subjects: "Python"
})

This finds documents whose subjects array contains the value "Python".

Example: Find Students with Programming Skills
db.array_students.find({
    skills: "Programming"
})

MongoDB matches the array element without requiring us to specify its index.

4. The $all Operator

The $all operator matches documents whose array contains every specified value. Other array elements may also be present.

Example
db.array_students.find({
    subjects: {
        $all: ["HTML", "CSS"]
    }
})

This finds students whose subjects array contains both HTML and CSS, regardless of the order of those values.

Another Example
db.array_students.find({
    skills: {
        $all: ["Design", "Programming"]
    }
})

This matches documents containing both specified skills in the array.

5. The $in Operator with Arrays

The $in operator matches documents when the field value matches at least one value from the specified list. For an array field, an element can match one of those values.

Example
db.array_students.find({
    subjects: {
        $in: ["Python", "Java"]
    }
})

This finds students whose subjects array contains Python or Java.

Difference Between $all and $in
  • $all requires every specified value to be present.
  • $in requires at least one specified value to match.

6. The $size Operator

The $size operator matches arrays containing exactly the specified number of elements.

Example: Students with Three Subjects
db.array_students.find({
    subjects: {
        $size: 3
    }
})

This finds students whose subjects array contains exactly three elements.

Example: Students with Two Skills
db.array_students.find({
    skills: {
        $size: 2
    }
})

The $size query operator checks for an exact array length. It does not directly support ranges such as "at least three elements."

7. The $push Operator

The $push operator adds a value to an array. If the array field does not exist, MongoDB creates it.

Example: Add a Subject
db.array_students.updateOne(
    { name: "Rahul" },
    {
        $push: {
            subjects: "MongoDB"
        }
    }
)

The value "MongoDB" is appended to Rahul's subjects array.

Add a Number to an Array
db.array_students.updateOne(
    { name: "Rahul" },
    {
        $push: {
            marks: 95
        }
    }
)

This appends 95 to the marks array.

8. The $addToSet Operator

The $addToSet operator adds a value only if an equal value is not already present in the array.

Example
db.array_students.updateOne(
    { name: "Rahul" },
    {
        $addToSet: {
            subjects: "Python"
        }
    }
)

If Python is already present, this operation does not add another equal value. Otherwise, it adds Python.

Use $push when duplicate values are acceptable, and $addToSet when you want to avoid adding duplicate values.

9. The $pull Operator

The $pull operator removes all array elements that match the specified value or condition.

Example: Remove a Subject
db.array_students.updateOne(
    { name: "Rahul" },
    {
        $pull: {
            subjects: "HTML"
        }
    }
)

This removes every occurrence of HTML from Rahul's subjects array.

Remove Marks Below 40
db.array_students.updateOne(
    { name: "Rahul" },
    {
        $pull: {
            marks: { $lt: 40 }
        }
    }
)

This removes all marks below 40 from the selected student's marks array.

10. The $pop Operator

The $pop operator removes one element from an array:

  • -1 removes the first element.
  • 1 removes the last element.
Remove the First Subject
db.array_students.updateOne(
    { name: "Rahul" },
    {
        $pop: {
            subjects: -1
        }
    }
)
Remove the Last Subject
db.array_students.updateOne(
    { name: "Rahul" },
    {
        $pop: {
            subjects: 1
        }
    }
)

These operations remove an element from the selected student's subjects array.

11. Query an Array by Index

MongoDB supports dot notation for matching a particular array position. Array indexes begin at zero.

Example: Match the First Subject
db.array_students.find({
    "subjects.0": "Java"
})

This finds documents where the first element of the subjects array is Java.

Example: Match the Second Mark
db.array_students.find({
    "marks.1": 85
})

This finds documents where the second element of the marks array equals 85.

12. Important Points to Remember

  • Arrays store multiple values in a single document field.
  • $all matches arrays containing all specified values.
  • $in matches when at least one specified value matches.
  • $size matches an exact array length.
  • $push appends a value, including duplicates.
  • $addToSet adds a value only if an equal value is not already present.
  • $pull removes all matching array elements.
  • $pop removes the first or last array element.
  • Use dot notation to query an array element by index.

13. Practical Assignment

Create a collection named practice_arrays and insert these documents:

db.practice_arrays.insertMany([
    {
        _id: 1,
        name: "Rahul",
        subjects: ["Java", "Python", "HTML"],
        marks: [70, 85, 90]
    },
    {
        _id: 2,
        name: "Priya",
        subjects: ["HTML", "CSS", "JavaScript"],
        marks: [80, 90, 95]
    },
    {
        _id: 3,
        name: "Aman",
        subjects: ["Python", "SQL"],
        marks: [60, 75]
    },
    {
        _id: 4,
        name: "Neha",
        subjects: ["Java", "CSS"],
        marks: [88, 92]
    }
])
Complete these tasks:
  1. Find students whose subjects array contains Python.
  2. Find students whose subjects array contains both HTML and CSS.
  3. Find students whose subjects array contains Java or SQL.
  4. Find students who have exactly two subjects.
  5. Add MongoDB to Rahul's subjects using $push.
  6. Add SQL to Priya's subjects using $addToSet.
  7. Remove HTML from Rahul's subjects using $pull.
  8. Remove the last subject from Neha's array using $pop.
  9. Find students whose first subject is Java.
  10. Display all updated documents using find().

Run the insertion command only once, or clear the test collection before inserting the same sample data again.

🧠 Quick Quiz

1. Which operator adds a value to an array?




2. Which operator adds a value only if an equal value is not already present?




3. Which operator removes all matching array elements?