What is the difference between save and insert in MongoDB?

10

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"});
    
asked by anonymous 27.07.2017 / 17:34

1 answer

11

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:

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

    
27.07.2017 / 17:37