Mongodb PHP不能推到数组的末尾



你好,我尝试了(实际上排列)在mongodb中插入数组的每一种方式,没有什么是我期望的工作方式。

这是我要放入

的文档结构
["test123"]=>
  array(6) {
    ["_id"]=>
    string(7) "test123"
    ["products"]=>
    array(1) {
      [0]=>
      array(9) {
        ["task_description"]=>
        string(0) ""
        ["priority"]=>
        string(4) "high"
        ["done"]=>
        string(4) "true"
        ["extended_price"]=>
        string(1) "0"
        ["unit_price"]=>
        string(1) "0"
        ["qty"]=>
        string(1) "0"
        ["description"]=>
        string(18) "sample description"
        ["item"]=>
        string(7) "Service"
        ["date_done"]=>
        string(10) "2013-06-03"
      }
    }
    ["total"]=>
    string(1) "0"
    ["tax"]=>
    string(1) "0"
    ["discount"]=>
    string(1) "0"
    ["currency"]=>
    string(3) "EUR"
  }
}

我想要push另一个格式为products[0]的数组到products。下面是我尝试使用的代码。

$collection->update(
        array("_id" => $id), 
        // THIS REPLACES [0] ELEMENT IN ARRAY 'PRODUCTS' BUT I DONT WANT THAT
        // array('$push' => array("products"=>array(0=>$data)))
            // THIS IS NOT WORKING AT ALL
        array('$push' => array('products' => $data))
        );

您看到的确切错误是什么?鉴于您共享的示例文档,我无法重现您的问题(products[0]被覆盖或模糊的"这根本不起作用"评论)。

我用下面的代码实现了预期的结果,它恰好与上面的代码匹配:

$m = new MongoClient();
$c = $m->test->foo;
$c->drop();
// Create a document with a "p" array containing one embedded object
$c->insert(['p' => [['a' => 1, 'b' => 1]]]);
// This would add a second element to the "p" array, which would be
// a single-element array containing our embedded object
$c->update([], ['$push' => ['p' => [0 => ['a' => 2, 'b' => 2]]]]);
// This appends an embedded object to the "p" array
$c->update([], ['$push' => ['p' => ['a' => 2, 'b' => 2]]]);
// Debugging
var_export(iterator_to_array($c->find()));

相关内容

  • 没有找到相关文章

最新更新