简体   繁体   中英

Update a field in mongodb collection even if it doesnt exist

I want to set isChecked field to mongodb collection even if this field does not exist in the collection:

User.updateOne({ id }, { $set: { isChecked: true } });

But it doesnt update because isChecked does not exist. I remember it was something with new but I dont remember exactly.

PS I love mongodb but I hate it's documentation. 0 readability

The behavior of this query should not depend on if isChecked exists; the $set operator will set the value of isChecked , regardless of if the field exists in the document before or not :

If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint.

Were you possibly thinking of upsert or some other behavior with incrementing?

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