Paramclasses Academy - Blog

Tutorials Details

←
Post 22 of 35
→

MongoDB Array Queries: Find and Update Array Elements

MongoDB Array Queries: Find and Update Array Elements

November 5, 2026

MongoDB Array Queries: Find and Update Array Elements

Introduction

MongoDB is a NoSQL database that stores data in flexible BSON documents. One of its useful features is the ability to store multiple values inside an array field.

For example, a student document can contain multiple skills, a product document can contain multiple tags, and an order document can contain multiple items.

Sometimes, developers need to find documents based on specific array values or update only selected elements without changing the entire array.

MongoDB provides several query operators and update techniques for handling these operations.

In this tutorial, you will learn how to search array elements using $in, $all, and $elemMatch, and how to update array elements using positional operators, arrayFilters, $addToSet, and $pull.

1. What Is an Array in MongoDB?

An array in MongoDB is a collection of values stored inside a single document field.

An array can contain:

  • Strings

  • Numbers

  • Objects

  • Other supported BSON values

Example:

{
  name: "Rahul",
  skills: ["HTML", "CSS", "JavaScript"]
}

Here:

  • name stores the student's name.

  • skills stores multiple values in an array.

  • Each skill is an individual array element.

MongoDB allows you to search and update these elements directly.

2. Create a Database and Collection

Let's create a sample database for practical examples.

Open MongoDB Shell (mongosh).

use collegeDB

Create a collection:

db.createCollection("students")

Insert sample documents:

db.students.insertMany([
  {
    name: "Rahul",
    age: 21,
    skills: ["HTML", "CSS", "JavaScript"],
    marks: [75, 85, 90]
  },
  {
    name: "Priya",
    age: 22,
    skills: ["Python", "Java", "MongoDB"],
    marks: [80, 88, 92]
  },
  {
    name: "Amit",
    age: 20,
    skills: ["C", "C++", "Java"],
    marks: [65, 70, 78]
  },
  {
    name: "Neha",
    age: 23,
    skills: ["HTML", "Python", "MongoDB"],
    marks: [90, 95, 98]
  }
])

Display all documents:

db.students.find()

Now we have a collection containing array fields that we can use in our examples.

3. How to Find Documents Using Array Values

MongoDB allows you to find documents by specifying a value inside an array field.

Example: Find students who have JavaScript as a skill.

db.students.find({
  skills: "JavaScript"
})

MongoDB returns documents where the skills array contains the value "JavaScript".

You do not need to specify an array index when searching for an individual value.

Example: Find students who have MongoDB as a skill.

db.students.find({
  skills: "MongoDB"
})

This query matches documents whose skills array contains MongoDB.

4. Using $in to Find Matching Array Elements

The $in operator selects documents where a field matches at least one value from a specified list.

Syntax:

db.collection.find({
  field: {
    $in: [value1, value2]
  }
})

Example:

db.students.find({
  skills: {
    $in: ["JavaScript", "Python"]
  }
})

This query returns students whose skills array contains JavaScript or Python.

Important: $in matches at least one specified value, not necessarily all values.

5. Using $all to Match Multiple Array Values

The $all operator selects documents whose array contains all the specified values.

Example: Find students who know both HTML and Python.

db.students.find({
  skills: {
    $all: ["HTML", "Python"]
  }
})

MongoDB returns documents where the skills array contains both HTML and Python.

The order of the values in the array does not matter for this query.

Difference between $in and $all:

Operator Purpose
$in Matches at least one specified value
$all Matches all specified values

6. Using $elemMatch to Find Array Elements

The $elemMatch operator selects documents where at least one array element satisfies all specified conditions.

It is especially useful when an array contains embedded documents.

Let's create another collection for practical examples:

db.createCollection("employees")

Insert employee documents:

db.employees.insertMany([
  {
    name: "Rahul",
    projects: [
      { title: "Website", status: "Completed", hours: 40 },
      { title: "App", status: "Pending", hours: 25 }
    ]
  },
  {
    name: "Priya",
    projects: [
      { title: "Ecommerce", status: "Completed", hours: 60 },
      { title: "Dashboard", status: "Completed", hours: 35 }
    ]
  },
  {
    name: "Amit",
    projects: [
      { title: "Website", status: "Pending", hours: 20 }
    ]
  }
])

Example: Find employees who have a completed project requiring more than 30 hours.

db.employees.find({
  projects: {
    $elemMatch: {
      status: "Completed",
      hours: { $gt: 30 }
    }
  }
})

Here:

  • projects is an array of embedded documents.

  • $elemMatch checks individual project objects.

  • status: "Completed" checks the project status.

  • $gt: 30 checks whether the project hours are greater than 30.

Both conditions must be satisfied by the same array element.

7. Find Array Elements Using Array Index

MongoDB also allows you to query an array using its element position.

Array indexing starts from zero.

Example: Find students whose first skill is HTML.

db.students.find({
  "skills.0": "HTML"
})

Here:

  • skills is the array field.

  • 0 represents the first array element.

  • "HTML" is the required value.

Example: Find students whose second skill is CSS.

db.students.find({
  "skills.1": "CSS"
})

This query checks the second element of the skills array.

8. How to Update an Entire Array

You can replace an existing array using the $set update operator.

Example: Update Rahul's complete skills array.

db.students.updateOne(
  { name: "Rahul" },
  {
    $set: {
      skills: ["HTML", "CSS", "React"]
    }
  }
)

This replaces the previous skills array with the new array.

Important: $set on an array field replaces the entire array. It does not update just one element.

9. How to Update a Specific Array Element Using the Positional $ Operator

MongoDB provides the positional $ operator to update the first array element that matches the query condition.

Example:

db.students.updateOne(
  {
    name: "Rahul",
    skills: "JavaScript"
  },
  {
    $set: {
      "skills.$": "TypeScript"
    }
  }
)

This updates the matching JavaScript element to TypeScript in Rahul's skills array.

Explanation:

  • name: "Rahul" identifies the student.

  • skills: "JavaScript" matches the required array element.

  • "skills.$" refers to the first matching array position.

  • $set changes that element.

Important: The positional $ operator requires the array field to be part of the query so MongoDB can identify the matching element.

10. How to Update Array Elements Using $[]

The $[] positional all operator updates every element in the specified array.

Example:

Suppose you want to increase every mark in Rahul's marks array by 5.

db.students.updateOne(
  { name: "Rahul" },
  {
    $inc: {
      "marks.$[]": 5
    }
  }
)

This increases every mark in Rahul's marks array by 5.

For example, the array:

[75, 85, 90]

Becomes:

[80, 90, 95]

Here, $inc increases numeric values by the specified amount.

11. How to Update Selected Array Elements Using arrayFilters

MongoDB provides arrayFilters to update only those array elements that match specific conditions.

This is useful when you want to update selected elements inside an array without changing all elements.

Example:

Increase only marks greater than or equal to 85 by 5.

db.students.updateOne(
  { name: "Rahul" },
  {
    $inc: {
      "marks.$[mark]": 5
    }
  },
  {
    arrayFilters: [
      { mark: { $gte: 85 } }
    ]
  }
)

Explanation:

  • marks.$[mark] identifies array elements using the filter identifier mark.

  • arrayFilters defines the condition.

  • $gte: 85 selects marks greater than or equal to 85.

  • $inc: 5 increases only the matching values.

If Rahul's marks were [75, 85, 90], they become [75, 90, 95].

12. Add New Elements Using $push

The $push operator adds a new element to an existing array.

Example: Add React to Rahul's skills.

db.students.updateOne(
  { name: "Rahul" },
  {
    $push: {
      skills: "React"
    }
  }
)

This adds React as a new element in the skills array.

If the same value is already present, $push can add another copy.

13. Add Unique Elements Using $addToSet

The $addToSet operator adds an element only if it does not already exist in the array.

Example:

db.students.updateOne(
  { name: "Rahul" },
  {
    $addToSet: {
      skills: "MongoDB"
    }
  }
)

If MongoDB is not already present, it is added.

If it already exists, MongoDB does not add another identical value.

Difference between $push and $addToSet:

Operator Purpose
$push Adds an element, including duplicates
$addToSet Adds an element only if an equal value is not already present

14. Remove Array Elements Using $pull

The $pull operator removes all array elements that match a specified condition.

Example: Remove C++ from Amit's skills.

db.students.updateOne(
  { name: "Amit" },
  {
    $pull: {
      skills: "C++"
    }
  }
)

This removes matching C++ values from Amit's skills array.

Example: Remove marks below 70.

db.students.updateOne(
  { name: "Amit" },
  {
    $pull: {
      marks: { $lt: 70 }
    }
  }
)

This removes all marks below 70 from Amit's marks array.

15. Important MongoDB Array Query and Update Operators

Operator Purpose
$in Matches at least one specified value
$all Matches all specified values
$elemMatch Matches array elements satisfying specified conditions
$ Updates the first matching array element
$[] Updates all array elements
$[identifier] Updates elements matching arrayFilters
$push Adds a new array element
$addToSet Adds an element only if an equal value is absent
$pull Removes matching array elements
$set Sets or replaces a field value
$inc Increases a numeric value

16. Best Practices for MongoDB Array Queries

Follow these practices when working with array fields:

  1. Use $in when at least one specified value should match.

  2. Use $all when every specified value must be present.

  3. Use $elemMatch when multiple conditions must match the same embedded array element.

  4. Use the positional $ operator when updating the first matching array element.

  5. Use $[] when every array element needs to be updated.

  6. Use arrayFilters when only selected array elements should be updated.

  7. Use $addToSet when duplicate values should be avoided.

  8. Use $pull to remove elements matching a condition.

  9. Avoid storing excessively large arrays in a single document. Consider MongoDB's document size limit and data-modeling recommendations.

  10. Verify array updates using find() after performing update operations.

17. Practical Exercise

Create a database named trainingDB and a collection named courses.

Insert documents with these fields:

  • studentName

  • skills

  • scores

  • courses

Now complete these tasks:

Task 1: Find students who have JavaScript in their skills array.

Task 2: Find students who have both HTML and CSS using $all.

Task 3: Find students whose scores array contains a value greater than 80.

Task 4: Add Python to a student's skills using $push.

Task 5: Add MongoDB without duplicates using $addToSet.

Task 6: Update the first matching skill using the positional $ operator.

Task 7: Increase every score using $[] and $inc.

Task 8: Update only selected scores using arrayFilters.

Task 9: Remove a skill using $pull.

Task 10: Verify all updated documents using find().

18. Frequently Asked Questions (FAQs)

Q1. What is an array in MongoDB?

An array is a field that stores multiple values inside a single MongoDB document.

Q2. How do I find a value inside a MongoDB array?

Use the array field name and the required value:

db.students.find({
  skills: "JavaScript"
})

Q3. What is the difference between $in and $all?

$in matches at least one specified value, whereas $all requires all specified values to be present in the array.

Q4. What is $elemMatch used for?

$elemMatch finds documents where at least one array element satisfies all specified conditions.

Q5. What is the positional $ operator in MongoDB?

The positional $ operator identifies the first array element matching the query condition so it can be updated.

Q6. What is the difference between $[] and $[identifier]?

$[] updates all array elements, while $[identifier] updates only elements that match the conditions defined in arrayFilters.

Q7. How can I add an element to an array in MongoDB?

Use $push to add an element or $addToSet to add it only when an equal element is not already present.

Q8. How can I remove an element from an array?

Use $pull with a value or condition to remove matching array elements.

Conclusion

MongoDB array queries are useful when applications need to store and manage multiple values inside a single document.

In this tutorial, we learned how to find array elements using $in, $all, and $elemMatch. We also explored array updates using the positional $ operator, $[], arrayFilters, $push, $addToSet, and $pull.

These techniques help developers manage complex document structures without unnecessarily replacing entire arrays.

Practice these examples in mongosh to improve your MongoDB array-query skills.

←
Post 22 of 35
→