db.collection.updateOne(
{ "key": 1 },
{ $set: { "name": "abc", "age": 20 } }, // The update operation using $set to update "name" and set "age" to 20
{ upsert: true } // Optional: Set to true to insert a new document if no matching document is found
);
2条答案
按热度按时间ia2d9nvy1#
您可以尝试使用findOneAndUpdate函数
参见https://sparkbyexamples.com/mongodb/mongodb-insert-if-not-exists/?amp=1
字符串
v9tzhpje2#
如果该字段不存在,
$set
将添加一个具有指定值的新字段doccumentation
字符串