App下載
話題 首頁 > MongoDB 教程 > MongoDB 教程話題列表 > 詳情

mongodb的save和insert函數(shù)的區(qū)別

精華
如此輕盈 2016-09-20 10:17:22 瀏覽(4874) 回復(fù)(5) 贊(0)
mongodb的save和insert函數(shù)的區(qū)別是什么呢?是什么呢?是什么呢?
mongodb

回答(5)

如此輕盈 2016-09-20

mongodb的save和insert函數(shù)都可以向collection里插入數(shù)據(jù),但兩者是有兩個區(qū)別:

一、使用save函數(shù)里,如果原來的對象不存在,那他們都可以向collection里插入數(shù)據(jù),如果已經(jīng)存在,save會調(diào)用update更新里面的記錄,而insert則會忽略操作

二、insert可以一次性插入一個列表,而不用遍歷,效率高, save則需要遍歷列表,一個個插入。

看下這兩個函數(shù)的原型就清楚了,直接輸入函數(shù)名便可以查看原型,下面標(biāo)紅的部分就是實現(xiàn)了循環(huán),對于遠程調(diào)用來說,是一性次將整個列表post過來讓mongodb去自己處理,效率會高些

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

下面是 python里的實現(xiàn)向mongo插入數(shù)據(jù)的代碼

import pymong

logItems =[]

logItems.append({"url":})

logItems.append({"url":})

logItems.append({"url":})

def addLogToMongo(db,logItems):

 #建立一個到mongo數(shù)據(jù)庫的連接
 con = pymongo.MongoClient(db,27017)
 #連接到指定數(shù)據(jù)庫
 db = con.my_collection    


 #直接插入數(shù)據(jù),logItems是一個列表變量,可以使用insert直接一次性向mongoDB插入整下列表,如果用save的話,需一使用for來循環(huán)一個個插入,效率不高
 db.logDetail.insert(logItems)
 '''
  for url in logItems:
      print(str(url))
      db.logDetail.save(url)
 '''
一筆荒蕪 2018-05-31

大神在哪里呀,大神在哪里呀,大神在哪里呀.

1144100656 2018-05-31

留名留名!!!,同樣的問題,看看咋結(jié)局!!!

1152696398 2018-05-31

這個問題我也不清楚,等大佬來解決吧。。

要回復(fù),請先登錄 或者注冊