0

My structure looks like this:

"_id" : { "$oid" : "502ac2858386b3f419000002"} ,
"eventName" : "eventA" ,
"eventStreamName" : "eventA-0001" ,
"encoders" : [ 
    { 
    "encoderName" : "enc-201" ,
    "streams" : [ 
        { "language" : "eng" , "format" : "flash" , "priority" : "primary"} ,
        { "language" : "spa" , "format" : "flash" , "priority" : "primary"} ,
        { "language" : "fra" , "format" : "flash" , "priority" : "primary"}
        ]
    } ,
    { 
    "encoderName" : "enc-202" ,
    "streams" : [ 
        { "language" : "eng" , "format" : "flash" , "priority" : "primary"} ,
        { "language" : "spa" , "format" : "flash" , "priority" : "primary"}   // i'd like to add stream here
        ]
    } 
]

I would like to push an item to the streams array where encoderName = 'enc-202' and eventName = 'eventA'

Here's what I've tried

    $this->liveEvents = $db->selectCollection("liveEvents");
    $newStream = array("language" => "ger",
            "format" => "flash",
            "priority" => "primary");

    $filter = array("eventName" => "eventA",
                    "encoders.encoderName" => "enc-202");
    $update = array('$push'=>array('encoders.streams'=>$newStream));

    $this->liveEvents->update($filter,$update);

but its not working. I'm not sure if I can add 2 items to my $filter, and my $update may be off too.

New to mongodb. Any help would be great. Thanks!

1 Answer 1

3

You're missing the part that tells mongo which sub-array that needs to be updated. By just passing the filter it's returning the entire object and then when you try and do the update it doesn't know which "encoder" array to update. This is remedied in Mongo by using the $ positional operator. See explanation here.

So your update statement should be:

$update = array('$push' => array('encoders.$.streams' => $newStream));

By adding in the positional operator Mongo then takes the filter and applies the update to the encoder that caused the filter to match.

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.