App下載
話題 首頁(yè) > MongoDB 教程 > MongoDB 教程話題列表 > 詳情

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

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

回答(5)

如此輕盈 2016-09-20

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

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

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

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

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里的實(shí)現(xiàn)向mongo插入數(shù)據(jù)的代碼

import pymong

logItems =[]

logItems.append({"url":})

logItems.append({"url":})

logItems.append({"url":})

def addLogToMongo(db,logItems):

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


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

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

1144100656 2018-05-31

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

1152696398 2018-05-31

這個(gè)問(wèn)題我也不清楚,等大佬來(lái)解決吧。。

要回復(fù),請(qǐng)先登錄 或者注冊(cè)