Dean219 Dean219 - 2 years ago 274
PHP Question

Mongodb insert into existing array

Hey im having issues inserting an element into an existing mongodb document.
At the moment there is an array containing a single element in my db :

$count = array();
array_push($count, 0);
$dbase->insert(array("_id"=> $_id,"count"=>$count));

However i now wish to insert a single element back into the "count array" and after looking around this was the recommended way:


However this is throwing an error (error 500, internal server error) and im unsure why. Iv also tried using insert but it results in the creation of a new document. Any help would be appreciated.

Answer Source

While I'm not exactly sure why you need an array here, there are a couple ways to update arrays and their members ...

Connect to the database/collection

$m = new MongoClient();
$db = $m->your_database;
$collection = $db->your_colection;

Update one member of the array

If you'd like to update one member of the array (in this case the 0 member) you would do ...

  array("_id"=> new MongoId("57b6556aa9087c06687ecd7c")),
  array('$set'=>array("count.0"=> 4))

Add to the array

If you want to add a new item to the array, your count you can do ...

  array("_id"=> new MongoId("57b6556aa9087c06687ecd7c")),
  array('$push'=>array("count"=> 4))

You would now have two members in the array.

Note: This will only work if count is indeed an array.

Update/change "count" to a number

  array("_id"=> new MongoId("57b35f7bce23505c10000029")), 
  array('$set'=>array("count"=> 4))

This will turn what was an array in a number.

Generally, I'd recommend not using a an array here unless you actually need to store multiple values.

Also, depending on your MongoDB PHP Driver version you may need to use:

new MongoDB\BSON\ObjectID(); instead of new MongoId();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download