2011-08-11 53 views
2

我有一個小問題,希望你能幫助我。 我在MongoDB的下一個數組結構:將數據插入到MongoDB的內部數組中

{ 
"_id":ObjectId("4e43cf96e7c7914b87d2e0ff"), 
"list" :[ 
    { 
    "id" : ObjectId("4e43cf96e62883ee06000002"), 
    "user_name" : "login", 
    "comments" : [ ] //insert here new data 
    }, 
    { 
    "id" : ObjectId("4e43cf96e62883ee06000003"), 
    "user_name" : "login", 
    "comments" : [ ] 
    } 
] 
} 

而且我想通過「list.id」新的數據插入到的意見。但我嘗試這樣的:

$post_id = "4e43cf96e62883ee06000002"; 
$this->connection->user->feed->update(
    array ('list.id' => new MongoId($post_id)), 
    array ('$push' => array ('list'=>array('comments'=>$data))) 
) 

但是,代碼創建結構新的領域,而不是將數據添加到外地 '意見':

{ 
"_id":ObjectId("4e43cf96e7c7914b87d2e0ff"), 
"list" :[ 
    { 
    "id" : ObjectId("4e43cf96e62883ee06000002"), 
    "user_name" : "login", 
    "comments" : [ ] //insert here new data 
    },  
    { 
    "id" : ObjectId("4e43cf96e62883ee06000003"), 
    "user_name" : "login", 
    "comments" : [ ] 
    },    
    { 
    "comments" : { //added new field 
     //there is my data 
    } 
] 
} 

我也試過:

$this->connection->user->feed->update(
    array ('list.id' => new MongoId($post_id)), 
    array ('$push' => array ('list.comments'=>$data)) 
); 

但沒有。

回答

10

這工作正常,在蒙戈控制檯:)

db.yar.update({"list.id":ObjectId("4e43cf96e62883ee06000002")}, {"$addToSet":{"list.$.comments":"my cool comment"}}); 
+0

是的,你是對的;)非常感謝你!你能告訴我什麼char「$」在「list。$。comments」中意味着什麼?或者給我一個參考?謝謝! –

+1

[鏈接到文檔](http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator) – Igorekk

1

使用$ addToSet修飾符,因爲註釋是數組而不是字段。

+0

我改變「$推」到「$ addToSet」,但該代碼具有相同的行爲與「$推」(添加新的領域,我將展示例子有問題) –

+0

,我也使用'$ push'將數據添加到'list'數組,並且它與'$ push'一起使用。 –

+0

或我在我的代碼中有一些錯誤? –