11
What difference in the Mongodb between insert item with save and with Insert ?
Example:
db.pessoa.insert({"nome":"João"});
db.pessoa.save({"nome":"Maria"});
11
What difference in the Mongodb between insert item with save and with Insert ?
Example:
db.pessoa.insert({"nome":"João"});
db.pessoa.save({"nome":"Maria"});
13
Insert will always create a new document while the save update an existing document, or insert a new one.
If you only run save without parentheses on the Mouse console db.teste.save
, the code of the function will be shown, it is easy to understand what it does so! Below the code shown in the console (mongod v3.4.2):
function (obj, opts) {
if (obj == null)
throw Error("can't save a null");
if (typeof(obj) == "number" || typeof(obj) == "string")
throw Error("can't save a number or string");
if (typeof(obj._id) == "undefined") {
obj._id = new ObjectId();
return this.insert(obj, opts);
} else {
return this.update({_id: obj._id}, obj, Object.merge({upsert: true}, opts));
}
}
Going over the code:
upsert: true
is held to update or insert the document.You can do the same thing with Insert db.teste.insert
. It is a much bigger function (I won’t paste here). Check her code, you will see that there is no verification to update the document.
Browser other questions tagged mongodb
You are not signed in. Login or sign up in order to post.