Python Pymongo中Connection()與MongoClient()差別

在git找了幾個blog的源碼,在學習的過程當中,發現有人使用Connection(),有人卻在使用MongoClient(),那麼到底二者有什麼差異呢?python

且看分析以下:git

db = Connection('192.168.1.101', 27017).performance_test 安全

#client = MongoClient('192.168.1.101', 27017)

#db = client.performance_test 

 db.drop_collection("updates") 

collection = db.updates 

collection.insert({"x": 1}) 

collection.find_one() 

start = time.time() 

for i in range(100000): 

        collection.update({}, {"$push" : {"x" : 1}}) 

...

運行結果: 服務器

>python test_mongo_conn.py性能

8.43799996376學習

>python test_mongo_client.pythis

62.5780000687spa

 

用Connection() 8秒,MongoClient()則花了62秒,這性能相差也太多了。code

 

非常疑惑,因而查了pymongo的文檔,原來二者有個選項的默認行爲不一樣:orm

  

class pymongo.connection.Connection([host='localhost'[, port=27017[, max_pool_size=10[, network_timeout=None[, document_class=dict[, tz_aware=False[, **kwargs]]]]]]])

Write Concern options:

safe: Connection disables acknowledgement of write operations. Use safe=True to enable write acknowledgement.

w: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. w=<int> always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to two secondaries). Implies safe=True.

wtimeout: (integer) Used in conjunction with w. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. Implies safe=True.

j: If True block until write operations have been committed to the journal. Ignored if the server is running without journaling. Implies safe=True.

fsync: If True force the database to fsync all files before returning. When used with j the server awaits the next group commit before returning. Implies safe=True.

 

 

safe選項決定操做是「瞬時完成」與「安全操做」,connection()默認是safe=False,即瞬時完成,不等服務器迴應,而MongoClient()默認是safe=True,即安全操做,等服務器確認後才繼續下一步操做。

因此一個8秒,一個62秒,這個差距其實是「瞬時完成」與「安全操做」二者的性能差異。

當將Connection() 和MongoClient()創建鏈接時指定相同的safe參數,二者的性能表現是同樣的。

 

client = MongoClient('192.168.1.101', 27017,safe=False)

#db = Connection('192.168.1.101', 27017,safe=False).performance_test 

結論:Python用Connection()鏈接時,修改操做速度很是快,而用MongoClient()創建的鏈接,操做速度慢不少。

順便分享帳號密碼登陸的代碼: 

 
from pymongo import MongoClient
client = MongoClient('www.yeayee.com','27017')
client.database.authenticate("user","password")
db = client.database
collection = db.collection
相關文章
相關標籤/搜索