博主自主知识产权《Spring Boot深入浅出系列课程》(16章97节文档) 已经上线,请关注

MongoDB的CRUD操作讲解-1-insert

mongodb 字母哥 0评论

插入操作

//插入一条数据
db.inventory.insert(
{
    item: "ABC1",
    details: {
        model: "14Q3",
        manufacturer: "XYZ Company"
    },
    stock: [ { size: "S", qty: 25 }, { size: "M", qty: 50 } ],
        category: "clothing"
    }
)
//验证插入是否成功
db.inventory.find()
//插入一组数据
var mydocuments =
[
    {
        item: "ABC2",
        details: { model: "14Q3", manufacturer: "M1 Corporation" },
        stock: [ { size: "M", qty: 50 } ],
        category: "clothing"
    },
    {
        item: "MNO2",
        details: { model: "14Q3", manufacturer: "ABC Company" },
        stock: [ { size: "S", qty: 5 }, { size: "M", qty: 5 }, { size: "L", qty: 1 } ],
        category: "clothing"
    },
    {
        item: "IJK2",
        details: { model: "14Q2", manufacturer: "M5 Corporation" },
        stock: [ { size: "S", qty: 5 }, { size: "L", qty: 1 } ],
        category: "houseware"
    }
];  
db.inventory.insert(mydocuments);
//使用Bulk进行批量插入
var bulk = db.inventory.initializeUnorderedBulkOp();
bulk.insert(
    {
            item: "BE10",
            details: { model: "14Q2", manufacturer: "XYZ Company" },
            stock: [ { size: "L", qty: 5 } ],
            category: "clothing"
    }
);
bulk.insert(
    {
            item: "ZYT1",
            details: { model: "14Q1", manufacturer: "ABC Company" },
            stock: [ { size: "S", qty: 5 }, { size: "M", qty: 5 } ],
            category: "houseware"
    }
);
bulk.execute();

比较insert和save方法

insert方法的源码

> db.user.insert
function (obj, _allow_dot) {
    if (!obj) {
        throw "no object passed to insert!";
    }
    if (!_allow_dot) {
        this._validateForStorage(obj);
    }
    if (typeof obj._id == "undefined" && !Array.isArray(obj)) {
        var tmp = obj;
        obj = {_id:new ObjectId};
        for (var key in tmp) {
            obj[key] = tmp[key];
        }
    }
    this._db._initExtraInfo();
    this._mongo.insert(this._fullName, obj);
    this._lastID = obj._id;
    this._db._getExtraInfo("Inserted");
}

save方法的源码

> db.user.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);
    }
}

区别:

  • 首先要知道,_id是唯一索引,在同一个集合内不能重复
  • 当使用insert方法,插入一条重复的id的文档时,文档插入失败
  • 当时用save方法,插入一条重复的id的文档时,save采用的方法是属性字段更新替换,id不变。
喜欢 (0)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址