简体   繁体   中英

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?

尝试$exists 运算符

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM