...">

Difference between db.collectionX.save and db.collectionX.insert

> itemsA = { attrA : "vA", attrB : "vB" }
{ "attrA" : "vA", "attrB" : "vB" }
> db.collectionA.insert(itemsA)
> db.collectionA.find()
{ "_id" : ObjectId("4e85de174808245ad59cc83f"), "attrA" : "vA", "attrB" : "vB" }
> itemsA
{ "attrA" : "vA", "attrB" : "vB" }


> itemsB = { attrC : "vC", attrD : "vD" }
{ "attrC" : "vC", "attrD" : "vD" }
> db.collectionB.save(itemsB)
> db.collectionB.find()
{ "_id" : ObjectId("4e85de474808245ad59cc840"), "attrC" : "vC", "attrD" : "vD" }
> itemsB
{
    "attrC" : "vC",
    "attrD" : "vD",
    "_id" : ObjectId("4e85de474808245ad59cc840")
}

Here is my observation:

After pasting into collectionA, the value of itemsA does not change.

In contrast, after saving to collectionB, the value of itemB is changed!

Is there any rule that guides these changes so that I know what to expect after the value is inserted or saved to the collection?

thank

+5
source share
2 answers

, _id, . , . Mongo JavaScript - , . , - MongoDB !

JS:

> db.test.save
function (obj) {
    if (obj == null || typeof obj == "undefined") {
        throw "can't save a null";
    }
    if (typeof obj == "number" || typeof obj == "string") {
        throw "can't save a number or string";
    }
    if (typeof obj._id == "undefined") {
        obj._id = new ObjectId;
        return this.insert(obj);
    } else {
        return this.update({_id:obj._id}, obj, true);
    }
}
> db.test.insert
function (obj, _allow_dot) {
    if (!obj) {
        throw "no object passed to insert!";
    }
    if (!_allow_dot) {
        this._validateForStorage(obj);
    }
    if (typeof obj._id == "undefined") {
        var tmp = obj;
        obj = {_id:new ObjectId};
        for (var key in tmp) {
            obj[key] = tmp[key];
        }
    }
    this._mongo.insert(this._fullName, obj);
    this._lastID = obj._id;
}

, save - .

, _id . , _id, save() , insert() .

+3

, _id, . , , .

+2

All Articles