MongoDB: Update Arrays in Documents
Learn how to update array fields in documents in MongoDB collections.
You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria.
It is recommended to use the updateMany()
method to update multiple arrays in a collection.
To demonstrate the update operation, insert the following sample documents in the employees
collection.
db.employees.insertMany([
{
_id:1,
firstName: "John",
lastName: "King",
email: "[email protected]",
salary: 5000,
skills: [ "Angular", "React", "MongoDB" ]
},
{
_id:2,
firstName: "Sachin",
lastName: "T",
email: "[email protected]",
salary: 8000,
skills: [ "Accounting", "Tax" ]
},
{
_id:3,
firstName: "James",
lastName: "Bond",
email: "[email protected]",
salary: 7500,
skills: [ "Sales", "Marketing" ]
},
{
_id:4,
firstName: "Steve",
lastName: "J",
email: "[email protected]",
salary: 7000,
skills: [ "Mac", "Marketing", "Product Design" ]
},
{
_id:5,
firstName: "Kapil",
lastName: "D",
email: "[email protected]",
salary: 4500,
skills: [ "Accounting", "Tax", "Sales" ]
},
{
_id:6,
firstName: "Amitabh",
lastName: "B",
email: "[email protected]",
salary: 7000,
skills: [ "Marketing", "Tax" ]
}
])
Overwrite Arrays
The $set
operator overwrites the specified array instead of adding, removing, and updating array elements.
db.employees.updateMany({_id:5},{$set:{ skills:["Sales Tax"]}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
In the above example, {$set:{ skills:["Sales Tax"]}}
overwrites an existing array for {_id:5}
.
db.employees.find({_id:5})
{
_id: 5,
firstName: 'Kapil',
lastName: 'D',
email: '[email protected]',
salary: 4500,
skills: [ 'Sales Tax' ],
department: { name: 'Finance' },
location: 'USA'
}
Update Array Elements
Use the array operators to update single or multiple elements of arrays in MongoDB.
The following will update "Marketing" to "Public Speaking" in the skills
array field to all the documents.
db.employees.updateMany(
{skills:"Marketing"},
{$set:{"skills.$":"Public Speaking"}})
{
acknowledged: true,
insertedId: null,
matchedCount: 2,
modifiedCount: 2,
upsertedCount: 0
}
In the above example, {skills:"Marketing"}
specifies the criteria to find all the documents where the skills
array contains "Marketing"
element.
Second parameter {$set:{"skills.$":"Public Speaking"}})
specifies the value to update using $set
operator.
The {"skills.$":"Public Speaking"}
specifies to update element to "Public Speaking".
The $
is an array operator that acts as a placeholder for the first match of the update query document.
db.employees.updateMany(
{},
{ $set: {"skills.$[element]":"GST"}},
{ arrayFilters: [{ element: "Tax" }]})
{
acknowledged: true,
insertedId: null,
matchedCount: 6,
modifiedCount: 2,
upsertedCount: 0
}
In the above example, { $set: {"skills.$[element]":"GST"}},{ arrayFilters: [{ element: "Tax" }]}
updates the skills
array if it contains "Tax" element then updates it to "GST".
{"skills.$[element]":"GST"}}
specifies to update element to "GST", and arrayFilters
specifies the criteria for array elements.
The { arrayFilters: [{ element: "Tax" }]}
specifies that the find array element whose value is "Tax".
So, the updateMany()
method will update array elements with the value specified by $set
and for the matching elements specified by arrayFilters
.
Add New Element to Arrays
Use the $push
array operator to add new elements to arrays.
The following will add "Sports"
element in all arrays.
db.employees.updateMany(
{},
{$push:{"skills":"Sports"}}) // add "Sports" to all arrays
db.employees.updateMany(
{_id:3},
{$push:{"skills":"Sports"}}) // add "Sports" element to skills array where _id:3
Use the $each
operator to specify multiple elements that needs to be added in the arrays.
db.employees.updateMany(
{},
{$push:{"skills":{$each:["Sports","Acting"]}}}) // adds "Sports" and "Acting" to all arrays
In the above example, {$each:["Sports","Acting"]}
specifies an array to add multiple elements.
Use $addToSet
operator to add an element if it does not already exist.
The following will add "GST"
to skills
array in all documents if it does not exist.
db.employees.updateMany(
{},
{ $addToSet: {"skills":"GST"} }) // adds "GST"to all arrays if not exist
Remove First or Last Element from Arrays
Use the $pop
operator to remove first or last element from arrays. Specify 1 to remove the last element and -1 to remove the first element.
db.employees.updateMany(
{},
{$pop:{"skills":1}}) // removes the last element
db.employees.updateMany(
{},
{$pop:{"skills":-1}}) //removes the first element
db.employees.updateMany(
{},
{$pull: { "skills": "GST" }}) // removes "GST"