开发者

Insert data into inner array in MongoDB

开发者 https://www.devze.com 2023-03-27 15:49 出处:网络
I have a little problem, hope You can help me. I have next array structure in MongoDB: { \"_id\":ObjectId(\"4e43cf96e7c7914b87d2e0ff\"),

I have a little problem, hope You can help me. I have next array structure in MongoDB:

{
"_id":ObjectId("4e43cf96e7c7914b87d2e0ff"),
"list" :[
    {
    "id" : ObjectId("4e43cf96e开发者_开发知识库62883ee06000002"),
    "user_name" : "login",
    "comments" : [ ]  //insert here new data
    },
    {
    "id" : ObjectId("4e43cf96e62883ee06000003"),
    "user_name" : "login",
    "comments" : [ ]
    }
]
}

And I want to insert new data to comments by "list.id". But I try like that:

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

But that code create new field in structure, but not add data to field '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
     }
]
}

Also I tried:

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

But nothing.


This works fine in mongo console :)

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


Use $addToSet modifier, because comments is a array not field.

0

精彩评论

暂无评论...
验证码 换一张
取 消