我想在MongoDB中更新我的子数组 这是MongoDB Collection的样子
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 );
似乎没有更新
答案 0 :(得分: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 :(得分:0)
正如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) );