Patrickkx
Patrickkx

Reputation: 1870

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.

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

Upvotes: 3

Views: 152

Answers (1)

Adam Harrison
Adam Harrison

Reputation: 3421

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?

Upvotes: 2

Related Questions