问题
This has to be easy, but i can't seem to figure it out... Let say i had a collection users
and this is the first item in the collection:
{
"_id" : ObjectId("4d8653c027d02a6437bc89ca"),
"name" : "Oscar Godson",
"email" : "oscargodson@xxx.com",
"password" : "xxxxxx",
"tasks" : [
{
"task" : "pick up stuff",
"comment" : "the one stuff over there"
},
{
"task" : "do more stuff",
"comment" : "lots and lots of stuff"
}
] }
How with the PHP driver for MongoDB would I then go and add another "task" to the "tasks" array in this item in a collection
回答1:
Use Mongo's $push
operation:
$new_task = array(
"task" => "do even more stuff",
"comment" => "this is the new task added"
);
$collection->update(
array("_id" => ObjectId("4d8653c027d02a6437bc89ca")),
array('$push' => array("tasks" => $new_task))
);
来源:https://stackoverflow.com/questions/5370925/mongodb-in-php-how-do-i-insert-items-into-an-array-in-a-collection