I am wanting to update my sub-array in MongoDB Here is what the MongoDB Collection looks like
array (
'_id' => new MongoId("510fb81638fc5d2966000000"),
'items' =>
array (
'0' =>
array (
'id' => '510bb69538fc5d0c2d000000',
'quantity' => '1',
),
'1' =>
array (
'id' => '510bca8138fc5d6e38000000',
'quantity' => '1',
),
),
'session' => '1359964785.85203874781',
'status' => 'cart'
)
I created my form to send the following
however when I try to $set it to mongo
$filter = array('session' => $_SESSION["redi-Shop"]);
$data2 = array(
'$set' => array($_POST['items'])
);
$options = array("upsert" => true);
$collection->update( $filter, $data2, $options );
Nothing seems to update
Sammaye
44k7 gold badges110 silver badges149 bronze badges
asked Feb 4, 2013 at 14:13
RussellHarrower
6,89825 gold badges113 silver badges228 bronze badges
-
Posting duplicates won't get your answer sooner: stackoverflow.com/questions/14687113/… finish the other firstSammaye– Sammaye2013年02月04日 14:16:01 +00:00Commented Feb 4, 2013 at 14:16
-
Not A duplicate question if you read that question and this question totally different as that question was inserting into a sub array this is updating the sub array - might seem same but very differentRussellHarrower– RussellHarrower2013年02月04日 14:20:31 +00:00Commented Feb 4, 2013 at 14:20
2 Answers 2
Your set is wrong:
$filter = array('session' => $_SESSION["redi-Shop"]);
$data2 = array('$set' =>array('items' => array($_POST['items'])));
$options = array("upsert" => true);
$collection->update( $filter, $data2, $options );
I should mention using the $_POST in this way is asking for some one to hack your shopping site.
answered Feb 4, 2013 at 14:32
Sammaye
44k7 gold badges110 silver badges149 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
mnemosyn
+1 for the remark on the slight lack of security in this approach
As Sammaye said, you've overlooked your query. And, do you want to update, replace or push to an array?
To replace all of items :
$data2 = array('$set' => array('items' => array($_POST['items'])));
$collection->update( array('session' => $_SESSION["redi-Shop"]), $data2, array("upsert" => true) );
To update the first array of items :
$data2 = array('$set' => array('items.0' => $_POST['items']));
$collection->update(array('session' => $_SESSION["redi-Shop"]), $data2, array("upsert" => true) );
And to push to the items array :
$data2 = array('$push' => array('items' => $_POST['items']));
$collection->update(array('session' => $_SESSION["redi-Shop"]), $data2, array("upsert" => true) );
answered Feb 4, 2013 at 14:59
Adil
2,1324 gold badges27 silver badges37 bronze badges
Comments
default