pymongo 模塊分析

    在pymongo 2.x版本中連接有'MongoClient', 'MongoReplicaSetClient','Connection'三種方式,其中'Connection'不建議使用。
    在pymongo 3.x版本中已經沒有了'Connection''MongoClient'是在pymongo中連接mongodb服務器的基礎類。

'''
Client for a MongoDB instance, a replica set, or a set of mongoses.
        The client object is thread-safe and has connection-pooling built in.
        If an operation fails because of a network error,
        :class:`~pymongo.errors.ConnectionFailure` is raised and the client
        reconnects in the background. Application code should handle this
        exception (recognizing that the operation failed) and then continue to
        execute.
'''

 'MongoReplicaSetClient'繼承了'MongoClient',其主要功能都差不多,可能在未來的版本中刪除
'''
:class:`~pymongo.mongo_replica_set_client.MongoReplicaSetClient`
    will be removed in a future version of PyMongo.
'''


'MongoClient'爲例來操作mongodb數據庫
pymongo連接mongodb服務器

conn = pymongo.MongoClient(hosts,replicaSet = replicaSet)
可以在連接時使用read_preference參數設置讀取偏好:先讀主庫還是從庫或者只讀主庫或只讀某一個,也可以使用MongoClient.get_database()獲取數據庫對象時設置,在2.x版本還可以直接設置read_preference的值,在3.x版本該值爲私有屬性。
MongoReplicaSetClient參數:
__init__(
            self,
            host=None,
            port=None,
            document_class=dict,
            tz_aware=False,
            connect=True,
            **kwargs):
host:
- `host` (optional): hostname or IP address of the
            instance to connect to, or a mongodb URI, or a list of
            hostnames / mongodb URIs. If `host` is an IPv6 literal
            it must be enclosed in '[' and ']' characters following
            the RFC2732 URL syntax (e.g. '[::1]' for localhost)

 **kwargs(其他超時設置等參數見源碼註釋):
'''
       - `replicaSet`: (string or None) The name of the replica set to
            connect to. The driver will verify that all servers it connects to
            match this name. Implies that the hosts specified are a seed list
            and the driver should attempt to find all members of the set.
            Defaults to ``None``.
          - `read_preference`: The read preference for this client. If
            connecting directly to a secondary then a read preference mode
            *other* than PRIMARY is required - otherwise all queries will throw
            :class:`~pymongo.errors.AutoReconnect` "not master".
            See :class:`~pymongo.read_preferences.ReadPreference` for all
            available read preference options. Defaults to ``PRIMARY``.
'''

獲取數據庫連接對象的幾種方式:
DB = conn[db_name]    #可能是在__getitem__方法內調用了get_database()
DB = conn.db_name      #可能是在__getattr__方法內調用了get_database()
DB = conn.get_database(db_name)
DB.authenticate(user,pwd)
返回pymongo.database.Database()實例化對象

對數據庫進行查詢
DB['__my_collection__'].find()
DB.__my_collection__.find()
使用DB['__my_collection__']和DB.__my_collection__時,pymongo.database.Database()的__getitem__和__getattr__方法實例化並返回一個pymongo.collection.Collection對象,然後使用該對象操作聚集。

以下是pymongo的部分方法(沒有仔細看,可能理解的不對)
#查詢方式
pymongo.ALL             #立即查詢
pymongo.SLOW_ONLY       #慢查詢
pymongo.OFF             #關閉查詢

#排序方式:
pymongo.ASCENDING           #增量排序
pymongo.DESCENDING          #倒序
#索引方式:
pymongo.GEO2D               #二維索引
pymongo.GEOHAYSTACK         #?
pymongo.GEOSPHERE           #球形空間索引(地理空間索引?)
pymongo.HASHED              #散列索引
pymongo.TEXT                #文本索引
#版本
pymongo.version_tuple = (3, 0, 1)   #版本號(元組)
pymongo.version = pymongo.get_version_string()  #版本號(字符串)
pymongo.get_version_string()    #將元組類型轉爲字符串
pymongo.MAX_SUPPORTED_WIRE_VERSION  #支持的mongodb版本(最大)
pymongo.MIN_SUPPORTED_WIRE_VERSION  #支持的mongodb版本(最小)

'''--------------------------------class CursorType---------------------------------------
'''
#遊標類型
pymongo.CursorType.EXHAUST          #批量獲取遊標
pymongo.CursorType.NON_TAILABLE     #標準遊標類型
pymongo.CursorType.TAILABLE         #tailable遊標類型
pymongo.CursorType.TAILABLE_AWAIT   #tailable遊標與等待選項設置

'''---------------------------class DeleteMany DeleteOne----------------------------------
'''
pymongo.DeleteMany                  #批量刪除操作(只有保護方法和內置方法)
pymongo.DeleteOne                   #刪除操作(只有保護方法和內置方法)

'''--------------------------------class IndexModel---------------------------------------
['_IndexModel__document', 'document']
'''
#應該是一個索引對象
pymongo.IndexModel.document         #應該是返回一個索引對象

'''---------------------------------class InsertOne---------------------------------------
'''
pymongo.InsertOne                   #插入操作(只有保護方法和內置方法)

'''---------------------------------class MongoClient---------------------------------------
'''
#pymongo.MongoClient.__init__(host, port, document_class, tz_aware, connect)
#獲取一個連接對象(可以是一個客戶端、副本集)
pymongo.MongoClient.arbiters        #返回複製集合列表(host,port)
pymongo.MongoClient.close           #關閉連接
pymongo.MongoClient.close_cursor    #關閉遊標
pymongo.MongoClient.codec_options   #獲取編碼
pymongo.MongoClient.database_names  #返回數據庫名稱
pymongo.MongoClient.drop_database   #刪除一個數據庫:參數爲數據庫名稱或一個pymongo.database.Database對象
pymongo.MongoClient.fsync           #立即同步數據到文件
pymongo.MongoClient.get_database    #獲取數據庫對象,並設置“讀取偏好”
pymongo.MongoClient.get_default_database#獲取連接的數據庫名稱    assert db.name == 'my_database'
pymongo.MongoClient.is_locked       #判斷數據庫是否加鎖(可讀不可寫)
pymongo.MongoClient.is_mongos       #連接的對象是不是mongo
pymongo.MongoClient.is_primary      #當前連接的是不是副本集的首個服務器或者獨立服務器
pymongo.MongoClient.kill_cursors    #通過cursor_id,kill cursor
pymongo.MongoClient.local_threshold_ms#不知道(返回當前連接?)
pymongo.MongoClient.max_bson_size   #獲取服務器最大接收字節數
pymongo.MongoClient.next            #pass
pymongo.MongoClient.nodes           #返回所有連接服務器列表
pymongo.MongoClient.primary         #獲取副本地址
pymongo.MongoClient.read_preference #獲取讀取偏好
pymongo.MongoClient.secondaries     #?
pymongo.MongoClient.server_info     #返回連接的服務器信息
pymongo.MongoClient.server_selection_timeout#返回查詢超時時間
pymongo.MongoClient.set_cursor_manager  #遊標管理
pymongo.MongoClient.unlock          #解鎖之前鎖定的服務器
pymongo.MongoClient.write_concern   #?







發佈了44 篇原創文章 · 獲贊 10 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章