Gary Kipnis Gary Kipnis - 1 year ago 42
Node.js Question

How to change one field in a structure that is part of an array in MongoDB using Node.JS

I have the following records in a collection:

id : id_value,
streams : [
{ a : a_value, b : b_value, c : c_value },
{ a : a_value, b : b_value, c : c_value }, ...

I want to be able to change the c_value of a particular entry in the streams array. I've been using a two step process of doing this, pulling out an entry from the streams array, creating a new entry and adding it back to the streams array. This works, but doesn't seem the most efficient way of accomplishing this. Is there a better approach that I can use? Below is the code that I'm currently using:

{$pull : {streams : {$and : [{a : a_value}, {b : b_value}]}}},
{w:1}, cb);

new_entry = { a : old_a_value, b : old_b_value, c : new_c_value}

{$addToSet : {streams : new_entry}}, {w:1}, cb);

Thank You,

Answer Source

An example atomic update which uses the $ positional operator to identify the document to update in the array follows:

    { "id": user, "streams.a": a_value, "streams.b": b_value },
    { "$set" : { "streams.$.c": new_c_value } },
    { "w": 1}, cb);