Just to sum up pymongo China and index Operation related functions , Commonly used are :

* create_index
* drop_index
* index_information
The most important of them is create_index, You can use it for mongo Of collection Index .
Here are some simple examples , The code is as follows :
>>>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 The function can also create an index using multiple fields , for example
>>>collection.create_index([('x',1),('y',1)])
In grammar (‘x’,1), x The value is the name of the index field to create ,1
Creates an index in ascending order for the specified , It can also be used pymongo.ASCENDING replace . If you want to create the index in descending order , Is specified as -1 or pymongo.DESCENDING.

in use create_index() When creating an index , You can also specify specific parameters (options), The common optional parameters are as follows :

Parameter name type description
backgroundBoolean The indexing process blocks other database operations ,background You can specify background mode to create index , That is, increase “background” Optional parameters .
“background” The default value is False.
uniqueBoolean Is the index created unique . Designated as True To create a unique index . The default value is False.
By default ,MongoDB A unique index field is generated when the collection is created _id.
namestring
The name of the index . If not specified ,MongoDB To generate an index name by joining the field name and sort order of the index . for example create_index([(‘x’,1)] When not specified name The default index name is generated
‘x_1’
expireAfterSecondsinteger Specifies a value in seconds , complete
TTL set up , Set the lifetime of the collection . You need to create a field with a date value or an array containing a date value .

Technology