Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To modify the value of an existing object in a MongoDB array, you can use the update method along with the $set operator to update specific fields within the object:

db.collection.update(
  { _id: ObjectId('12345') },
  { $set: { 'array.$.field': 'new value' } }
);

In the above example, collection is the name of the MongoDB collection, _id is the identifier of the document that contains the array, 12345 is the value of the _id field, array is the name of the field that contains the array, field is the name of the field within each object that represents the value you want to modify, and new value is the updated value.

To add a new object to the array, you can use the update method along with the $push operator:

db.collection.update(
  { _id: ObjectId('12345') },
  { $push: { array: { field1: 'value1', field2: 'value2' } } }
);

In this example, array is the name of the field that contains the array, and the new object { field1: 'value1', field2: 'value2' } is added to the end of the array.