Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB insert field to existing document if does not already exist

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?

like image 553
tpae Avatar asked Jul 19 '12 05:07

tpae


1 Answers

Try the $exists operator:

$this->mongolib->update('people', array('age' => array('$exists' => false)), array('$set' => array('age' => 14)), array('upsert' => true, 'multiple' => true));
like image 169
MrKurt Avatar answered Oct 11 '22 20:10

MrKurt