2011-08-11 51 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

或我在我的代码中有一些错误? –