Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

push new value to mongodb inner array - mongodb/php

Tags:

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?

like image 509
Rizky Ramadhan Avatar asked Jan 09 '11 08:01

Rizky Ramadhan


People also ask

How do I add values to an array in MongoDB?

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.

How do I update a nested array in MongoDB?

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.

How do you update an array object in MongoDB?

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>] .

How do I push into nested array?

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!


1 Answers

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.

like image 184
Justin Jenkins Avatar answered Oct 16 '22 08:10

Justin Jenkins