2

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.

2 Answers 2

10

This works fine in mongo console :)

db.yar.update({"list.id":ObjectId("4e43cf96e62883ee06000002")}, {"$addToSet":{"list.$.comments":"my cool comment"}});
Sign up to request clarification or add additional context in comments.

2 Comments

yea, You're right;) thank You a lot!! And can You tell me please what does char "$" means in "list.$.comments"? Or give me a reference? Thanks!
1

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

2 Comments

I change '$push' to '$addToSet', but that code has same behavior as with '$push' (add new field, I show example in question)
and also I use '$push' to add data to 'list' array, and it works with '$push'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.