I’m experimenting with MongoDB using the PHP PECL extension, however I’m having difficulty getting a certain update query to work. I have searched around on SO for answers with little luck.
I have created a basic collection:
$m = new Mongo;
$collection = $m->testdb->testcollection;
$collection->insert(array(
0, 1, 1, 2, 3, 5
));
Using findOne and var_dump the record appears as follows:
array
'_id' =>
object(MongoId)[6]
public '$id' => string '4f3bde65a1f7a0315b000000' (length=24)
0 => int 0
1 => int 1
2 => int 1
3 => int 2
4 => int 3
5 => int 5
The problem comes when I want to update using $set. I am basing my query on the mapping shown towards the bottom of the SQL to Mongo Cheat Sheet in the PHP manual
Here I want to update field 0 to value 100
$obj = $collection->findOne();
$collection->update(
array('_id' => $obj['_id']),
array('$set' => array(0 => 100))
);
Re-fetching the record shows that it remains unchanged.
I did wonder if I was doing something wrong with the _id, however the following update query does work, albeit replacing the entire record with a new value, not simply updating the one field.
$collection->update(
array('_id' => $obj['_id']),
array(0 => 100)
);
Object dump:
array
'_id' =>
object(MongoId)[7]
public '$id' => string '4f3bde65a1f7a0315b000000' (length=24)
0 => int 100
Can someone please point out what I am doing wrong, and how to properly use $set. I’m sure it’s obvious and I just need a second pair of eyes on it.
Many thanks.
I’ve doing some investigations to why this happens. And I don’t think I can find a way on how to “fix” this issue.
JavaScript has a difference between arrays and associative arrays/objects. PHP has the difference between arrays and objects. For PHP an associative array is an array, and for JavaScript it is an object.
When the PHP driver needs to convert an array to a JSON object, it tries to figure out whether an array is either: a normal array with sequentially numbered keys starting with 0; or an associative array. The current implementation regards any array with sequentially numbered keys, starting from 0 an normal array. And a normal array does not contain keys. And this is the problem. In the situation the driver sees a normal array, there is no field name information in the BSON that’s send to the server, and hence the server can’t update a field.
I can’t think of a way to change this behaviour without breaking any sort of existing code. So if you want numerical fieldnames, you will have to use a stdClass object for the “main document”. Alternatively, you could push those keys into a embedded document and then update:
<?php $m = new Mongo; $collection = $m->demo->testcollection; $collection->insert(array( "_id" => 'bug341', 'data' => array( 0, 1, 1, 2, 3, 5 ) )); $obj = $collection->findOne(); $update = array('data.0' => 'zero int'); $collection->update( array( '_id' => 'bug341' ), array( '$set' => $update ) ); $obj = $collection->findOne(); var_dump($obj); ?>