mongodb insert 命令中是否有“upsert”选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19974216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there an "upsert" option in the mongodb insert command?
提问by astroanu
I know this may be a silly question, but I read on an e-book that there is an upsert
option in MongoDB insert. I couldn't find proper documentation about this. Can someone educate me about this?
我知道这可能是一个愚蠢的问题,但我在一本电子书中读到upsert
MongoDB 插入中有一个选项。我找不到关于此的适当文档。有人可以教育我吗?
回答by zero323
Since upsert
is defined as operation that "creates a new document when no document matches the query criteria" there is no place for upserts
in insert
command. It is an option for the update
command. If you execute command like below it works as an update
, if there is a document matching query
, or as an insert
with document described by update
as an argument.
由于upsert
被定义为“当没有文档与查询条件匹配时创建一个新文档”的操作,因此没有地方供upserts
ininsert
命令使用。它是update
命令的一个选项。如果你像下面这样执行命令,它可以作为一个文件update
,如果有一个匹配的文件query
,或者作为一个insert
由update
参数描述的文件。
db.collection.update(query, update, {upsert: true})
MongoDB 3.2 adds replaceOne
:
MongoDB 3.2 添加replaceOne
:
db.collection.replaceOne(query, replacement, {upsert: true})
which has similar behavior, but its replacement
cannot contain update operators.
它具有类似的行为,但它replacement
不能包含更新运算符。
回答by glormph
As in the links provided by PKD, db.collection.insert()
provides no upsert possibility. Instead, mongo insert inserts a new document into a collection. Upsert is only possible using db.collection.update()
and db.collection.save()
.
与 PKDdb.collection.insert()
提供的链接一样,不提供 upsert 可能性。相反,mongo insert 将新文档插入到集合中。Upsert 只能使用db.collection.update()
and db.collection.save()
。
If you happen to pass a document to db.collection.insert()
which is already in the collection and thus has an _id
similar to an existing _id
, it will throw a duplicate key exception.
如果您碰巧传递了一个文档,db.collection.insert()
该文档已经在集合中,因此_id
与现有的相似_id
,它将抛出重复键异常。