Reputation: 21058
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!
Upvotes: 0
Views: 1512
Reputation: 46
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.
Upvotes: 3