mongodb之insert和save函数的区别

MongDB有个很方便的地方,只打函数的名字而不加括号,就能查看该函数的功能用法:
> 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");
}
> 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);
}
}
由上面可以看出,save函数实际就是根据参数条件,调用了insert或update函数.如果想插入的数据对象存在,insert函数会报错,而save函数是改变原来的对象;如果想插入的对象不存在,那么它们执行相同的插入操作.这里可以用几个字来概括它们两的区别,即所谓"有则改之,无则加之".

相关文章:

MongoDB基本操作指南
NoSQL数据库
MongoDB集群
MongoDB数据库
MongoDB备份与恢复
8种NoSQL数据库对比
配置mongodb分片群集(sharding cluster)
记一次MongoDB性能问题,附原理解析
mongodb之insert和save函数的区别
mongodb shell无法删除问题 与 secureCRT使用退格键出现^H解决办法
Mongodb源码分析之Mongos分析
PHP操作MongoDB

来源:互联网

发表评论