Modifying Arrays in MongoDB: A Comprehensive Guide

Learn how to effectively update array fields within MongoDB documents using the updateOne() and updateMany() methods. This guide will cover various update operators and techniques, allowing you to modify array elements, add new elements, remove existing elements, and more. Master array manipulation in MongoDB to enhance your data management capabilities.



MongoDB: Update Arrays in Documents

Learn how to update array fields in MongoDB collections using updateOne() or updateMany() methods. Use updateMany() to update multiple arrays in a collection.

Sample Data

Syntax

db.employees.insertMany([
    { _id: 1, firstName: "John", lastName: "Doe", email: "john.doe@example.com", salary: 5000, skills: ["JavaScript", "Node.js", "MongoDB"] },
    { _id: 2, firstName: "Jane", lastName: "Smith", email: "jane.smith@example.com", salary: 7000, skills: ["Accounting", "Finance"] },
    { _id: 3, firstName: "Emily", lastName: "Johnson", email: "emily.johnson@example.com", salary: 6000, skills: ["Sales", "Marketing"] }
])
Output

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 3,
  modifiedCount: 0,
  upsertedCount: 0
}

Overwrite Arrays

The $set operator replaces the specified array. Use it to set a new array value.

Syntax

db.employees.updateMany({_id: 2}, {$set: {skills: ["Finance Management"]}})
Output

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Check Updated Document

Syntax

db.employees.find({_id: 2})
Output

{
    _id: 2,
    firstName: 'Jane',
    lastName: 'Smith',
    email: 'jane.smith@example.com',
    salary: 7000,
    skills: ['Finance Management']
}

Update Array Elements

Use array operators to modify single or multiple array elements.

Syntax

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

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Add New Element to Arrays

Use the $push operator to add new elements to arrays.

Syntax

db.employees.updateMany(
    {},
    { $push: { skills: "Leadership" } }
)
Output

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 3,
  modifiedCount: 3,
  upsertedCount: 0
}

Add Element If Not Exist

The $addToSet operator adds an element if it is not already present.

Syntax

db.employees.updateMany(
    {},
    { $addToSet: { skills: "Leadership" } }
)
Output

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 3,
  modifiedCount: 0,
  upsertedCount: 0
}

Remove First or Last Element

Use the $pop operator to remove the first or last element from arrays. Specify 1 to remove the last element and -1 to remove the first element.

Syntax

db.employees.updateMany(
    {},
    { $pop: { skills: 1 } }
)
Output

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 3,
  modifiedCount: 3,
  upsertedCount: 0
}