Tuesday, 20 September 2011

MongoDb numeric field selection in PHP

If you are attempting to use numeric field selection with MongoCollection::find() and run into the error:

PHP Fatal error:  Uncaught exception 'MongoException' with message 'field names must be strings'

It is caused by PHP converting an array key that is defined as a string into an integer, so:

array('123' => 0);


array(123 => 0);

Unfortunately mongo requires strings for all field names.  A quick workaround (found after browsing code, not yet documented) to the problem is to use an object instead of an array:

$fields = new stdClass;
$fields->{123} = 0;

Problem solved.