MongoDB inserts a field into an existing document, if it is not already

I have a document like this (this is very simplified):

{
    'name' : 'test',
    'age' : 16
}

as well as this

{
    'name' : 'test2'
}

I want to set the "age" value to 14 for all if it does not exist.

How can i do this?

+5
source share
2 answers

Try to do $exists:

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

I have a roundabout way that I can think of. I suggest you use the regular update command, but just add the regular expression condition in the selection criteria to match only those documents that do not have the value (or numeric value) set for the age attribute.

0
source

All Articles