在Mongo DB中保存和插入有什么区别? [英] What is the difference between save and insert in Mongo DB?
问题描述
在Mongo DB中保存和插入有什么区别? 两者看起来都一样
What is the difference between save and insert in Mongo DB? both looks the same
db.users.save({username:"google",password:"google123"})
db.users.insert({username:"google",password:"google123"})
推荐答案
保存与插入:
在您给出的示例中,行为基本相同.
In your given examples, the behavior is essentially the same.
save
与"_id"参数一起传递,则其行为会有所不同.
save
behaves differently if it is passed with an "_id" parameter.
为保存起见,如果文档包含_id
,它将在_id
字段上查询查询集合,否则将插入.
For save, If the document contains _id
, it will upsert querying the collection on the _id
field, If not, it will insert.
如果不存在具有指定_id值的文档,则save()方法将对文档中的指定字段执行插入操作.
If a document does not exist with the specified _id value, the save() method performs an insert with the specified fields in the document.
如果存在具有指定_id值的文档,则save()方法将执行更新,将现有记录中的所有字段替换为该文档中的字段.
If a document exists with the specified _id value, the save() method performs an update, replacing all field in the existing record with the fields from the document.
保存与更新:
update
修改与查询参数匹配的现有文档.如果没有这样的匹配文档,那就是upsert
出现的时候.
-
upsert : false
:不存在此类文档时什么也不会发生 -
upsert : true
:新文档的创建内容等于查询参数和更新参数
upsert : false
: Nothing happens when no such document existupsert : true
: New doc gets created with contents equal to query params and update params
save
:不允许任何查询参数.如果_id
存在并且匹配的文档具有相同的_id
,它将替换它.如果未指定_id/没有匹配的文档,则会将其作为新文档插入.
save
: Doesn't allow any query-params. if _id
exists and there is a matching doc with the same _id
, it replaces it. When no _id specified/no matching document, it inserts the document as a new one.
这篇关于在Mongo DB中保存和插入有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!