What difference does the MongoDB difference between insert insert with save and with insert?
Example:
db.pessoa.insert({"nome":"João"});
db.pessoa.save({"nome":"Maria"});
What difference does the MongoDB difference between insert insert with save and with insert?
Example:
db.pessoa.insert({"nome":"João"});
db.pessoa.save({"nome":"Maria"});
Insert will always create a new document while save updates an existing document, or inserts a new one.
If you execute only the save function without the parentheses in the% s console, the function code will be shown, it is easy to understand what it does! Below the code shown on 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));
}
}
Reviewing the code:
db.teste.save
is done to update or insert the document. >
You can do the same with insert upsert: true
. It is a much larger function (I will not glue here). Check her code, you will see that you do not have any verification to update the document.