mongodb 不存在就插入

发布时间 2023-10-26 16:00:42作者: 秋来叶黄

不存在插入,存在不做任何处理。

db.companies.updateOne(
   {"company": "test"},
   { $setOnInsert: { "name": "nameVal2", ... } },
   { upsert: true }
)

{"company": "test"}是匹配条件

{ $setOnInsert: { "name": "nameVal2", ... } } 查询不到就会插入这里设定的值

{ upsert: true } 开启upsert

如果是项不存在插入,存在更新,请查看findandmodify/findoneandupdate

https://stackoverflow.com/questions/48220677/mongodb-how-to-insert-only-if-does-not-exists-no-update-if-exist