1

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:

 $count=4;
 $dbase->update(array('_id'=>'57b35f7bce23505c10000029'),array('$count'=>$count));

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.

1
  • 1
    Note you are trying to update $count with the value of the PHP variable $count ... this will not work as you are expecting, see my answer below. Commented Aug 19, 2016 at 1:04

1 Answer 1

1

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

$collection->update(
  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 ...

$collection->update(
  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

$collection->update(
  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();

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks the one that i meant was your Add to the array solution thanks for clarifying so thoroughly too you cleared up a lot of questions i had about mongodb through php, the documentation seemed to be littered with version for different version of php which made it confusing to find what i was looking for, so thanks again.
@Dean219, no problem! I agree, the official PHP docs are rather confusing & could use some simple, more straight forward examples. :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.