Open In App

Updating a Property of an Object in an Array within a MongoDB Document

In MongoDB, it’s common to store complex data structures within documents, including arrays of objects. Updating the property of an object within such an array can be a frequent requirement in many applications. This article will explore various methods to achieve this task, covering concepts like array filters, positional operators, and update operators. We’ll provide detailed examples and explanations to ensure a thorough understanding, even for beginners.

Updating Property in Array Object – MongoDB

Consider a MongoDB collection called users, where each document represents a user profile. Each user document contains an array of contacts, where each contact object has properties like name, email, and phone. Our goal is to update the email of a specific contact for a given user.



  1. Using Array Filters
  2. Using Positional Operators

1. Using Array Filters

Array filters allow precise updates to specific elements within an array based on specified criteria.

Example: Updating User Contact Email

Suppose we want to update the contact’s email with a name equal to “John” for the user with _id equal to “user123“.



db.users.updateOne(
{ _id: "user123" },
{ $set: { "contacts.$[element].email": "newemail@example.com" } },
{ arrayFilters: [{ "element.name": "John" }] }
);

Explanation:

Output:

The output of the updateOne operation will confirm the number of documents matched and modified.

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

The output confirms that one document in the collection was found and successfully modified as a result of the update operation.

2. Using Positional Operators

Positional operators allow for updating the first matched element in an array without explicitly specifying its index.

Example: Updating User Contact Email for “John”

To update the email of the contact with name equal to “John” for the user with _id equal to “user123“:

db.users.updateOne(
{ _id: "user123", "contacts.name": "John" },
{ $set: { "contacts.$.email": "newemail@example.com" } }
);

Explanation:

Output:

The output will indicate the number of documents matched and modified, as in the previous method.

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

The output confirms that one document in the collection was found and successfully modified as a result of the update operation.

Conclusion

Updating a property of an object within an array in a MongoDB document involves utilizing array filters or positional operators along with update operators like $set. By understanding these methods and their usage, you can efficiently update specific elements within arrays in your MongoDB documents. Experiment with different scenarios and adapt these techniques to suit your application’s requirements.

Article Tags :