问题描述
如何在不存在的情况下插入文档,而在不存在的情况下不更新现有文档呢?
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.
推荐答案
您可以使用 $ setOnInsert 之类的
db.getCollection('companies').update(
{"company": "test"},
{ $setOnInsert: { "name": "nameVal2", ... } },
{ upsert: true }
)
如果此查询未插入,则$setOnInsert
将不起作用.因此,名称只会在插入时更新.
If this query does not do insert, $setOnInsert
won't have any effect. So, the name will be updated only on insert.
这篇关于Mongodb如何仅在不存在时插入(如果存在则不更新)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!