empujar un nuevo valor a la matriz interna de mongodb - mongodb / php

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"]
}

intento esto:

$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?

preguntado el 09 de enero de 11 a las 08:01

5 Respuestas

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")));

Hay un problema con tu $push statement, you are not pushing "done_by" with a value of "2" you are actually sending "done_by" y "2" ...

Here is the issue ...

array('$push' => array("done_by","2"))

This should have a => no es un ,

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.

Respondido el 10 de enero de 11 a las 01:01

$filter = array('_id'=>$id));
$update = array('$push'=>array('done_by'=>'2'));
$q->update($filter,$update);

Respondido el 10 de enero de 11 a las 01:01

$push => array('done_by' => '2')

So says the manual: { $push : { field : value } }

Respondido el 10 de enero de 11 a las 00:01

$filter = array('_id'=>$id));
$update = array('$addToSet'=>array('done_by'=>'2'));
$q->update($filter,$update);

When you need to update use $addToSet so you avoid duplicate inserts which leads to multiple entries.

Respondido 05 Feb 18, 08:02

u can use as this :

$conn = new Mongo();
$q = $conn->server->gameQueue;
$id = new MongoId("4d0b9c7a8b012fe287547157");
$q->update(array("_id"=>$id),array('$addToSet' => array("done_by","2")));

Respondido 09 Abr '14, 11:04

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.