简体   繁体   中英

PHP updating MongoDB sub array

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM