1

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:

db.users.update({id:user},
    {$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} 

db.users.update({id:user},
    {$addToSet : {streams : new_entry}}, {w:1}, cb);

Thank You, Gary

1 Answer 1

1

If more than one field is being matched in the array record, then $elemMatch is required.

When matching just one field of an array record, then below works:

db.users.update(
    { "id": user, "streams.a": a_value},
    { "$set" : { "streams.$.c": new_c_value } },
    { "w": 1}, cb);

When matching more than one field of an array record, then $elemMatch is required as shown below:

db.users.update(
    { "id": user, streams: {$elemMatch : {a:a_value, b:b_value}},
    { "$set" : { "streams.$.c": new_c_value } },
    { "w": 1}, cb);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.