Thursday, July 26, 2018

PHP Mongodb Insert/Update Document with Array

http://php.net/manual/en/class.mongodb-driver-manager.php
$conn = new Mongo();
$q = $conn->server->gameQueue;
$id = new MongoId("4d0b9c7a8b012fe287547157");
$q->update(array("_id"=>$id),array('$push' => array("done_by","2")));
There is a problem with your $push statement, you are not pushing "done_by" with a value of "2" you are actually sending "done_by" and "2" ...
Here is the issue ...
array('$push' => array("done_by","2"))
This should have a => not a ,
array('$push' => array("done_by" => "2"))
However, note that every time you run this it will insert another "2" if you want MongoDB to only inset "2" if it doesn't already exist in "done_by" then you should use $addToSet ...
array('$addToSet' => array("done_by" => "2"))
This statement won't add 2 everytime, only the first time.

Credit:
https://stackoverflow.com/questions/4638368/push-new-value-to-mongodb-inner-array-mongodb-php