您的位置:首页 > 编程语言 > Go语言

pymongo 模块分析

2015-09-09 19:41 555 查看
    在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 Ins
4000
ertOne---------------------------------------
'''
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   #?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python pymongo