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 に答える