How to insert an object into another object within an array in mongo How to insert an object into another object within an array in mongo express express

How to insert an object into another object within an array in mongo


You need to have the index of the object you want to change, then you write it like this:

'array.index.keyToUpdate'.

If you have the index of the object before the update operation you can do it like this:

{$set: { 'employee.<indexToChange>.pay': 400 }}.

To make it dynamic and based on the query you can do:

update({ 'employee.name': 'Bob' }, {$set: { 'employee.$.pay': 400 }}).

In this case the $ stands for the first matched object in the array.