2012-08-01 68 views
0

我的MongoDB的內容(當我用find()方法)是這樣的:如何在MongoDB中插入數組值(php)?

{ "_id" : ObjectId("50072b17b4a6de3b11000001"), "addresses" : [ 
    { 
      "_id" : ObjectId("50072b17b4a6de3b11000004"), 
      "address1" : "770 27th Ave", 
      "address2" : null, 
      "city" : "San Mateo", 
      "country" : "United States", 
      "country_code" : "US", 
      "name" : "home", 
      "primary" : true, 
      "state" : "California", 
      "zip" : "94403" 
    } 
], "biography" : null, "category_ids" : [ ], "department" : null, "emails" : [ 
    { 
      "_id" : ObjectId("50072b17b4a6de3b11000003"), 
      "_type" : "Email", 
      "name" : "work", 
      "email" : "[email protected]" 
    } 
] } 

我需要做的是我需要額外DATAS的更新此MongoDB的。爲此,我需要在php中以數組的形式獲取值,並將該數組插入到此集合中。如何獲取這些指定字段的值作爲一個數組在PHP中,以及如何插入這些在PHP?

+0

您是否試圖[插入新文件]( http://php.net/manual/en/mongocollection.insert.php)或者[更新並保存](http://www.php.net/manual/en/mongocollection.save.php)更改爲「已檢索?正如您在其中一個相關問題上所建議的,值得花時間閱讀[PHP MongoDB驅動教程](http://php.net/manual/en/mongo.tutorial.php),因爲它包括所有的基礎知識。 – Stennie 2012-08-01 13:48:06

+0

@Stennie正在嘗試插入新文檔。 btw插入一個數組很簡單。但是當你在插入多維數組時看到上面的例子,每個內部數組都有單獨的對象ID。這意味着每個內部數組是另一個對象。如何插入這樣的數組? – user1554472 2012-08-01 16:38:07

回答

0
$array = $this->collection->findOne(array('_id' => MONGO_ID)); 
//Update things 
$this->collection->update(array('_id' => $array['_id']), $array); 

我的例子中的MONGO_ID應該代表MongoDB自動分配的'_id'。確保它作爲對象發送,而不是字符串。

+0

這是爲了更新現有的數據。當我想插入一個新的數據(我的意思是用新的對象ID)怎麼辦? – user1554472 2012-08-02 04:54:08

0

如果要添加其他的記錄,您可以添加一個條目,像這樣:

$this->collection->insert($array_of_data, array('safe' => true)); 
0

對於插入:

$id = new MongoId(); 
$test->insert(array('t' => 'test', 'email' => array('_id' => $id, 'email' => '[email protected]'))); 

而結果:

{ "_id" : ObjectId("5088cba86527044a31000001"), "t" : "test", "email" : { "_id" : ObjectId("5088cba86527044a31000000"), "email" : "[email protected]" } } 

它的工作原理: )

相關問題