• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:8 mins read
You are currently viewing MongoDB Change all array elements in a document to a certain value

How to change all array elements in a document to a certain value in MongoDB? In this article, we will explore how to change all array elements in a document to a certain value, using different methods and scenarios.

Advertisements

Let’s take a document that contains the array we want to update. For example, a collection named student with the document that contains two arrays as grades and courses.


#Create Collection
db.student.insertMany([
    { 
        _id:1,
        name: "Bella Jeo",
        courses: [ "python", "java", "php" ],
        grades: [ 75, 80, 90 ]
    },
    { 
       _id:2,
        name: "Tyler Reed",
        courses: [ "calculus", "data structure", "python" ],
        grades: [ 95, 80, 75 ]
    },
    { 
       _id:3,
        name: "Ian Kalus",
        courses: [ "web technologies", "perl", "python" ],
        grades: [ 91, 80, 100 ]
    },
    { 
        _id:4,
        name: "Niki Swift",
        courses: [ "java", "database", "php" ],
        grades: [ 70, 80, 90]
    }
])

1. Use $set Operator with $[] to Change All Array Elements

To change all array elements in a document to a certain value use the $set operator with $[]. The $set operator is used to set the value of a field in a document. When used in conjunction with the $[] operator, it can set the value of all elements in an array field that match the query condition.

Now, Let’s use these operators in the following query to change the array elements of the specified document. Here, the update() operation uses the $[] operator to identify all elements in the “grades” array of the “student” collection with the “_id” equals “2” and the $set operator to set the value of each element to “100“.


# Using $set and $[]operator
# to change array elements
db.student.update(
   { "_id": 2 },
   { "$set": { "grades.$[]": 100 } }
)

The results show that document whose array element needed to be changed is matched and modified.

Change array elements in MongoDB

Hence, the following output ensures the change of the grades array of all elements. This can be achieved using the find() method with a query that matches the modified document.

Change array elements in MongoDB

2. Changing All Array Elements of Multiple Documents in MongoDB

Likewise, if we want to change all the array elements of multiple documents then we again use the $set operator with the $[] operator. In this case, we have used the update method to update all documents in the student collection. We use an empty query object to match all documents, and then use the $set operator to set all the elements in the grades array to a value 200 using the $[] positional operator.

Furthermore, the {multi: true} option ensures that all matching documents are updated.


#Using $set and $[]operator 
# to change all array elements of multiple documents
db.student.update({}, {$set: {"grades.$[]": 200}}, {multi: true})

All the documents are matched and modified by the above query as displayed in the output:

The modified documents look like this:

More details about the $[] operator here.

3. Change Array Elements by using the Aggregation Framework in MongoDB

Although, we can use the aggregation framework to replace all elements in the array with a certain value. In the following aggregation example, we used the $match operator to filter the document, the $addFields operator adds a new field with the python array, the $map operator here replaces all elements and the $out operator changes the existing collection student with the updated one.


#Using $match, $addFields, $map and $out operator
db.student.aggregate([
    { "$match": { "_id": 3 } },
    { "$addFields": { "courses": { "$map": { "input": "$courses", "in": "python" } } } },
    { "$out": "student" }
])

The updated array is yielded in the output: 

Change array elements in MongoDB

4. By using the $push operator

Alternatively, we have a $push operator approach to add elements to an array in a document.

Here, multiple elements are added to an array at once by using the $push operator in conjunction with the $each method. However, it can also be used to replace all existing elements in an array with a new set of elements.

Consider the query where we add an empty array with the $push operator. After that, replace all existing elements with a new set of elements MongoDB, HTML, and Linux using the $each option.


# Using $push operator
db.student.update(
   { "name": "Niki Swift" },
   { "$push": { "courses": { "$each": ["MongoDB", "HTML", "Linux"]} } }
)

The confirmation output from MongoDB is retrieved below.

Change array elements in MongoDB

Now, the modified document looks like this:

Change array elements in MongoDB

5. Conclusion

MongoDB provides several ways to change array elements in a document to a certain value in MongoDB. The $[] operator is a powerful tool that allows us to change all elements in an array or only specific ones that match filter criteria. By combining it with other MongoDB operators and options, we can perform complex updates on our data with ease.