Hayk Safaryan Hayk Safaryan - 8 months ago 50
Node.js Question

MongoDB push data to specific array element

Hi guys so I'm doing meteor mongo db, I use findAndModify package


//Find the desired document based on specified criteria
query: {
"ipAdr": clientIp,
connections: {
$elemMatch: {
connID: clientConnId

//Update only the elements of the array where the specified criteria matches
update: {
$push: {
'connections': {
vid: result.data.vid,
firstName: result.data.properties.firstname.value,
lastName: result.data.properties.lastname.value
}); //Ips.findAndModify

So I find the element that I need however my info is being pushed to the whole connections array, but I want to push my info into that specific element. What should I do here? I tried

$push: {
'connections.$': {
vid: result.data.vid,

but it gives error.
Please help.


You don't need to use the $push operator here as it adds a new element to array, instead you need to modify an element that is already in the array, try the $set operator to update as follows:

update: {
        $set: {
          'connections.$.vid': result.data.vid,
          'connections.$.firstName': result.data.properties.firstname.value,
          'connections.$.lastName': result.data.properties.lastname.value

Take into account that this way you will change only one element of the array that satisfies the condition from the $elemMatch statement.