MongoDB: Update Arrays in Documents for expert

0 0
Read Time:3 Minute, 42 Second

You can use the updateOne() or updateMany() methods in MongoDB 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.

Sample Data

db.employees.insertMany([
    { 
        _id:1,
        firstName: "John",
        lastName: "King",
        email: "john.king@abc.com",
        salary: 5000,
        skills: [ "Angular", "React", "MongoDB" ]
    },
    { 
        _id:2,
        firstName: "Sachin",
        lastName: "T",
        email: "sachin.t@abc.com",
        salary: 8000,
        skills: [ "Accounting", "Tax" ]
    },
    { 
        _id:3,
        firstName: "James",
        lastName: "Bond",
        email: "jamesb@abc.com",
        salary: 7500,
        skills: [ "Sales", "Marketing" ]
    },
    { 
        _id:4,
        firstName: "Steve",
        lastName: "J",
        email: "steve.j@abc.com",
        salary: 7000,
        skills: [ "Mac", "Marketing", "Product Design" ]
    },
    { 
        _id:5,
        firstName: "Kapil",
        lastName: "D",
        email: "kapil.d@abc.com",
        salary: 4500,
        skills: [ "Accounting", "Tax", "Sales" ]
    },
    { 
        _id:6,
        firstName: "Amitabh",
        lastName: "B",
        email: "amitabh.b@abc.com",
        salary: 7000,
        skills: [ "Marketing", "Tax" ]
    }
])

Overwrite Arrays in MongoDB

The $set operator overwrites the specified array instead of adding, removing, and updating array elements.

Example: Overwrite Array 

db.employees.updateMany({_id:5},{$set:{ skills:["Sales Tax"]}})

Output

{
  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}.

Check Updated Document

db.employees.find({_id:5})

Output

 {
    _id: 5,
    firstName: 'Kapil',
    lastName: 'D',
    email: 'kapil.d@abc.com',
    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.

Example: Update Array Elements

db.employees.updateMany(
    {skills:"Marketing"},
    {$set:{"skills.$":"Public Speaking"}})

Output

{
  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.

Example: Update Array Elements

db.employees.updateMany(
    {}, 
    { $set: {"skills.$[element]":"GST"}},
    { arrayFilters: [{ element: "Tax" }]})

Output

{
  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.

Example: Add Array Elements

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.

Example: Add Array Elements

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.

Example: Add Element If Not Exist

db.employees.updateMany(
    {},
    { $addToSet: {"skills":"GST"} }) // adds "GST"to all arrays if not exist

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.

Example: Delete Array 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" 
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Comment