21

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Rizky Ramadhan
  • 7,360
  • 4
  • 27
  • 31

5 Answers5

43

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.

Justin Jenkins
  • 26,590
  • 6
  • 68
  • 1,285
4
$filter = array('_id'=>$id));
$update = array('$push'=>array('done_by'=>'2'));
$q->update($filter,$update);
Bob
  • 671
  • 1
  • 7
  • 12
2

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

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

chx
  • 11,270
  • 7
  • 55
  • 129
0
$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.

Graham
  • 7,431
  • 18
  • 59
  • 84
CKL
  • 1
  • 1
-1

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