2013-06-03 47 views
0

你好,我試過(實際上排列)插入到MongoDB中的數組中的每一種方式,沒有什麼工作如何我期待它。mongodb php不能推到陣列末尾

這是我想推入

["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" 
    } 
} 

文檔的結構欲推另一陣列中的產品[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)) 
     ); 

回答

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()));