简单总结一下pymongo中与index操做相关一些函数, 经常使用的有:python
其中最主要的是create_index, 能够用它来为mongo的collection创建索引。
如下操做一些简单的例子,代码以下:web
>>>import pymongo as pm >>>client = pm.MongoClient('mongodb://user:password@127.0.0.1:27017, ssl=True, ssl_ca_certs='/tmp/mongo_local.pem') >>>db = client['my_db'] >>>collection = db['my_collection'] #list all index related methods >>>print([x for x in dir(collection]) if 'index' in x) #['Collection__create_index', 'create_index','create_indexes','drop_index','drop_indexes',\ # 'ensure_index','index_information','list_indexes','reindex'] #create a index on attr. x >>>collection.create_index([('x',1)], unique = True, background = True) #get more help using help method >>>help(collection.create_index) #show index information collection.index_infomation() #{ # '_id_': {'key' ['_id',1)], 'ns':'my_db.my_collection', 'v':1}, # 'x_1' : { 'unique':True, 'key': [('x',1)], 'ns':'my_db.my_collection', 'v':1} #} #drop an index by index specifier >>>collection.drop_index([('x',1)]) #drop an index by index name >>>#collection.drop_index('x_1') #WARN: if an index is create with option name specified, it can only be dropped by name >>>collection.create_index([('x',1)], name = 'idx_x') >>>collection.drop_index('idx_x')
create_index函数也能够使用多个字段建立索引,例如mongodb
>>>collection.create_index([('x',1),('y',1)])
语法中(‘x’,1), x 值为要建立的索引字段名,1 为指定按升序建立索引,也能够用pymongo.ASCENDING代替。若是你想按降序来建立索引,则指定为 -1 或 pymongo.DESCENDING.数据库
在使用create_index()建立索引时,也可指定特定的参数(options),经常使用可选参数以下:数组
参数名 | 类型 | 描述 |
---|---|---|
background | Boolean | 建索引过程会阻塞其它数据库操做,background可指定之后台方式建立索引,即增长 “background” 可选参数。 “background” 默认值为False。 |
unique | Boolean | 创建的索引是否惟一。指定为True来建立惟一索引。默认值为False. 默认状况下,MongoDB在建立集合时会生成惟一索引字段_id。 |
name | string | 索引的名称。若是未指定,MongoDB的经过链接索引的字段名和排序顺序生成一个索引名称。例如create_index([(‘x’,1)]在不指定name时会生成默认的索引名称 ‘x_1’ |
expireAfterSeconds | integer | 指定一个以秒为单位的数值,完成 TTL设定,设定集合的生存时间。须要在值为日期或包含日期值的数组的字段的建立。 |