i have this document in mongo:
{ "_id": ObjectId("4d0b9c7a8b012fe287547157"), "done_by": ["1"] }
and i want to add another value to "done_by" field, so my expected document will be::
{ "_id": ObjectId("4d0b9c7a8b012fe287547157"), "done_by": ["1","2","3"] }
i try this:
$conn = new Mongo(); $q = $conn->server->gameQueue; $id = new MongoId("4d0b9c7a8b012fe287547157"); $q->update(array("_id"=>$id),array('$push' => array("done_by","2")));
but nothing happens, anyone know how to do this?
If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents.
Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.
To project, or return, an array element from a read operation, see the $ projection operator instead. To update all elements in an array, see the all positional operator $[] instead. To update all elements that match an array filter condition or conditions, see the filtered positional operator instead $[<identifier>] .
2) HOW TO ACCESS A NESTED ARRAY log(arr[0][0]); // Foo console. log(arr[0][1]); // Bar // (C) SECOND ELEMENT - ARR[1] IS AN OBJECT console. log(arr[1]['name']); // Jon console. log(arr[1]['gender']); // M // (D) THIRD ELEMENT - ARR[2] IS A FUNCTION arr[2]("TEST!"); // TEST!
Since neither of these answers are actually telling you what's wrong here ...
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With