Ask Your Question
4

How can we modify the value of an existing object in a MongoDB array or add a new object to the array?

asked 2021-12-10 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-10-09 19:00:00 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-10 11:00:00 +0000

Seen: 12 times

Last updated: Oct 09 '21