Mongodb如何仅在不存在时插入(如果存在则不更新)? [英] Mongodb how to insert ONLY if does not exists (no update if exist)?
本文介绍了Mongodb如何仅在不存在时插入(如果存在则不更新)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不存在的情况下插入文档,而在不存在的情况下不更新现有文档呢?
How can I insert a document if it does not exist while not updating existing document if it exists?
假设我有一个文档,如下所示:
let's say I have a document as follows:
{
"company":"test",
"name":"nameVal"
}
我想检查集合中是否包含公司test
,如果该公司不存在,我想创建一个新文档.如果存在,我什么也不想做.我用upsert = true
尝试了update
.但是它会更新现有文档(如果存在).
I want to check whether the collection contains company test
, if it doesn't exist I want to create a new document. If it exists I want to do NOTHING. I tried update
with upsert = true
. But it updates the existing document if it exists.
这是我尝试过的:
db.getCollection('companies').update(
{
"company": "test"
},
{
"company": "test",
"name": "nameVal2"
},
{upsert:true}
)
赞赏所有帮助您使用一个查询解决此问题的方法.
Appreciate any help to resolve this using one query.
推荐答案
查看全文