errmsg unauthorized when using PHP, mongoDB and mongoLabs.

While creating a DB migration script, we stumbled into a problem where commands using the PHP Mongo command “execute”, ironically weren’t being executed. The very short response message from the command read:

'errmsg' => 'unauthorized'

After much googling, a none accepted answer in this stackoverflow link suggested that “certain” versions of the PHP mongo command request authorisation against the admin DB (which I don’t have as I’m using mongoLabs).

The solution was to use the PHP Mongo ‘Update’ rather than ‘execute’ and likely the command I should have been using previously:

Before:

$db = $m->selectDB($this->config->db['collection']);
$db->execute('db.markup.update({}, {$rename: {"master_markup": "origin"}}, false, true);');

After:

$collection = new \MongoCollection($db, 'markup');
$collection->update(array(), array('$rename' => array('master_markup' => 'origin')), array('multiple' => true));

Just in case anyone else finds this useful, or can shed further light on why this happens, below are the various pieces of version information:

Versions:

mongoLab:   mongod 2.4.9 (Sandbox)
PHP:        PHP 5.4.30-2+deb.sury.org~precise+1
PECL:       1.4.5

Ben Squire

Read more posts by this author.

Leicestershire, United Kingdom https://squired.co.uk