Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert data into inner array in MongoDB

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

{
"_id":ObjectId("4e43cf96e7c7914b87d2e0ff"),
"list" :[
    {
    "id" : ObjectId("4e43cf96e62883ee06000002"),
    "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.

like image 339
Yaroslav Boichuk Avatar asked May 25 '26 04:05

Yaroslav Boichuk


1 Answers

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

like image 57
Igorekk Avatar answered May 27 '26 16:05

Igorekk