class MongoClient(pymongo.common.BaseObject)
Connection to MongoDB.
Method resolution order:
MongoClient
pymongo.common.BaseObject
__builtin__.object
class Connection(pymongo.mongo_client.MongoClient)
Connection to MongoDB.
Method resolution order:
Connection
pymongo.mongo_client.MongoClient
pymongo.common.BaseObject
__builtin__.object
我們先看一下源碼,從這兩個類的繼承來看,connection是繼承了MongoClient的,建議使用MongoClient而不是使用Connection。(也就是說,MongoClient可以使用方法Connection都可以使用)
from pymongo import MongoClient
client = MongoClient('192.168.40.87', 27037)
db_name = 'TCL_Useraction'
db = client[db_name]
collection_useraction = db['useraction']
這里是通過字典的方式訪問數據庫和集合,同時你也可以通過.(點號)的方式訪問
做實驗時,發現Python用Connection()連接時,修改操作速度非常快,而用MongoClient()建立的連接,操作速度慢很多。
from pymongo import MongoClient,Connection
import time
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.py
62.5780000687
用Connection() 8秒,MongoClient()則花了62秒,這性能相差也太多了。
很是疑惑,於是查了pymongo的文檔,原來兩者有個選項的默認行為不同:
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)
---------------------
作者:djd已經存在
來源:CSDN
原文:https://blog.csdn.net/djd1234567/article/details/47859015
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!