MongoDB insert field to existing document if does not already exist

mongodb, php-mongodb

Solution

Try the `$exists` operator:

$this->mongolib->update('people', array('age' => array('$exists' => false)), array('$set' => array('age' => 14)), array('upsert' => true, 'multiple' => true));

Problem

I have a document like this (this is very simplified): ``` { 'name' : 'test', 'age' : 16 } ``` and also this ``` { 'name' : 'test2' } ``` I want to set all 'age' to 14 if it does not exist. How can I do this?

Original source