2013-07-30 36 views
0

我是新來NoSQLMongoDB和我試圖$pusharray到另一個領域是一個array

我試圖push$dynamicInfo到我的用戶profile.weightTracker,這樣我可以有一個new arrayweightTracker當前代碼推代替,但我每次刷新頁面時不pusharray作爲new array /運行憑證,而是重新 - 寫入當前。

任何人都可以指出我做錯了什麼?

在此先感謝。

$dynamicInfo['currentWeight'] = '83'; 

$user = $this->db()->users; 

// Deals with the static info that just need an update 
if (empty($staticInfo) == false) { 
    $user->update(
     array('_id' => new MongoId($userId)), 
     array('$set' => array('profile' => $staticInfo)), 
     array('upsert' => True) 
    ); 
} 

// Deals with the dynamic info that needs to be inserted as array 
if (empty($dynamicInfo) == false) { 
    //$dynamicInfo['inserted_on'] = new MongoDate(); 
    $user->update(
     array('_id' => new MongoId($userId)), 
     array('$push' => array('profile.weightTracker' => $dynamicInfo)), 
     array('safe' => True) 
    ); 
} 

enter image description here

回答

2

我會期待將與靜態信息涉及代碼超過寫道,與動態信息再次只是第一個數組元素涉及每次運行時的文件,然後將代碼。換句話說,我不認爲$staticInfo當你期望它是空的。

如果你這樣做:

$user->update(
    array('_id' => 42), 
    array('$set' => array('profile.weightTracker' => array('height' => 82))) 
); 

然後:

$user->update(
    array('_id' => 42), 
    array('$set' => array('profile' => array('height' => 176))) 
); 

然後整個陣列profile將被設置爲array('height' => 176)。如果您之前將'profile.weightTracker'設置爲其他某個值,則無關緊要。

您不能設置數組(profile),並期望第一次更新(profiler.weightTracker)中未指定的子密鑰能夠存活。

但是,你可以做的是這樣的 - 只是建立在$set陣列和一氣呵成運行更新:

$user->update(
    array('_id' => 42), 
    array(
     '$push' => array('profile.weightTracker' => array('currentWeight' => 82)), 
     '$set' => array('profile.height' => 176) 
    ) 
); 
+0

我想先執行的一個更新的另一個根據是否自變量被設置。 –

+0

是的,我意識到這一點。但我無法猜測你的變量的內容是什麼! – Derick

+0

也許現在答案更清楚了? – Derick

相關問題