0

您好,我尝试了(实际上是置换的)在 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"
  }
}

我想以 products[0] 的格式将另一个数组推送到产品。这是我尝试使用的代码。

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

1 回答 1

0

您看到的确切错误是什么?鉴于您共享的示例文档,我无法重现您的任何一个问题(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()));
于 2013-06-24T21:14:47.627 回答