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("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.
精彩评论