0

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

2
  • Posting duplicates won't get your answer sooner: stackoverflow.com/questions/14687113/… finish the other first Commented 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 different Commented Feb 4, 2013 at 14:20

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the remark on the slight lack of security in this approach
0

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) );

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.