I have a structure like this:
[_id] => MongoId Object (
[$id] => 4e91bcb40b7aab256c000000
)
[campaigns] => Array (
[0] => Array (
[campaign_id] => 4e91bcd10b7aab2b6c000000
[refer_code] => AjZCJR
[owner] => 1
[campaign_name] => Test Campaign
[users] => Array (
)
)
[1开发者_开发问答] => Array (
[campaign_id] => 4e9210600b7aab276c000000
[refer_code] => FQIMJd
[owner] => 1
[campaign_name] => New Test Campaign
[users] => Array (
)
)
)
I would like to be able to update the campaigns array with new fields and update the existing fields, on the match of the ID.
Currently I am trying to do the following:
$data = array('campaign_name'=>'changed', 'new_field'=>'its new');
User::update(array('$push'=>array('campaigns.$'=>$data)),array('campaigns.campaign_id'=>$campaign_id));
However that is not working - I'm using the positional operator in order to try and match the array to the condition statement, as without it, it just creates a new array within the campaigns array.
I understand I am probably using it wrong, as I presume it should be used by doing
'campaigns.$.campaign_name'=>'changed'
However I don't want to be limited to specifying it each time, and was wondering the best way to do this type of update without using a for loop and adding each piece of data (which I'm currently doing as follows:)
$data = array();
foreach($this->request->data as $key=>$value) {
$data['campaigns.$.'.$key] = $value;
}
User::update($data,array('campaigns.campaign_id'=>$campaign_id));
If someone could let me know the 'proper' way to do this, that would be great!
Thanks :)
Dan
Just update:
$co = array(
'$pull' => array('campaigns.1" => array('campaign_name' => 'changed'' ) )
);
$p->update(array("_id" => new MongoId( $MongoID )), $co);
精彩评论