【问题标题】:PHP updating MongoDB sub arrayPHP更新MongoDB子数组
【发布时间】:2013-02-04 14:13:15
【问题描述】:

我想在 MongoDB 中更新我的子数组 这是 MongoDB 集合的样子

    array (
      '_id' => new MongoId("510fb81638fc5d2966000000"),
      'items' => 
      array (
        '0' => 
        array (
          'id' => '510bb69538fc5d0c2d000000',
          'quantity' => '1',
        ),
        '1' => 
        array (
          'id' => '510bca8138fc5d6e38000000',
          'quantity' => '1',
        ),
      ),
      'session' => '1359964785.85203874781',
      'status' => 'cart'
)

我创建了我的表单来发送以下内容

但是当我尝试将它设置为 mongo 时

$filter =  array('session' => $_SESSION["redi-Shop"]);
$data2 = array(
                '$set' => array($_POST['items'])
            );
$options = array("upsert" => true);
$collection->update( $filter, $data2, $options );

似乎没有更新

【问题讨论】:

  • 发布重复不会很快得到你的答案:stackoverflow.com/questions/14687113/… 先完成另一个
  • 不是一个重复的问题,如果您阅读了该问题并且这个问题完全不同,因为该问题被插入到子数组中,这正在更新子数组 - 可能看起来相同但非常不同

标签: php mongodb


【解决方案1】:

你的设置错了:

$filter =  array('session' => $_SESSION["redi-Shop"]);
$data2 = array('$set' =>array('items' => array($_POST['items'])));

$options = array("upsert" => true);
$collection->update( $filter, $data2, $options );

我应该提到,以这种方式使用$_POST 是在要求某人入侵您的购物网站。

【讨论】:

  • +1 表示关于 slight 这种方法缺乏安全性
【解决方案2】:

正如 Sammaye 所说,您忽略了您的查询。而且,您要更新、替换还是推送到数组?

替换所有项目:

$data2 = array('$set' => array('items' => array($_POST['items'])));
$collection->update( array('session' => $_SESSION["redi-Shop"]), $data2, array("upsert" => true) );

更新第一个项目数组:

$data2 = array('$set' => array('items.0' => $_POST['items']));
$collection->update(array('session' => $_SESSION["redi-Shop"]), $data2, array("upsert" => true) );

然后推送到 items 数组:

$data2 = array('$push' => array('items' => $_POST['items']));
$collection->update(array('session' => $_SESSION["redi-Shop"]), $data2, array("upsert" => true) );

【讨论】:

    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    相关资源
    最近更新 更多