What is the difference between save and Insert in Mongodb?

Asked

Viewed 744 times

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"});

1 answer

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:

  • An error is thrown if what you pass null, only a number or only a string.
  • If you pass a document without _id completed, it is generated and a Insert is performed.
  • If you completed the _id, one update with the option 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

You are not signed in. Login or sign up in order to post.