Mongodb如何仅在不存在时插入(如果存在则不更新)?

编程入门 行业动态 更新时间:2024-10-27 13:34:08
本文介绍了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.

推荐答案

您可以使用 $ 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如何仅在不存在时插入(如果存在则不更新)?

本文发布于:2023-10-28 18:49:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537471.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   Mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!