我有一点问题,希望你能帮助我.我在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 ) )) )
但是该代码在结构中创建了新字段,但没有向字段'comments'添加数据:
{ "_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 ) ) );
但没什么.
这在mongo控制台上运行良好:)
db.yar.update({"list.id":ObjectId("4e43cf96e62883ee06000002")}, {"$addToSet":{"list.$.comments":"my cool comment"}});