1、可以使用ensure_index或者create_index方法
首先,连接数据库中的目标集合:
col = MongoClient(the_client).get_database(the_db).get_collection(the_col)
然后,创建唯一索引,不加unique的话默认是普通的索引,即unique=False:
col.create_index([("索引字段名", 1)], unique=True)
或者,
col.ensure_index([("索引字段名", 1)], unique=True)
其中的1和-1分别表示正序与负序排列。注意,索引要用中括号——[ ("索引",1)],具体参见下方源码说明。
实例:
# -*- coding:utf-8 -*-
# 给mongodb集合创建索引
from pymongo import MongoClient
def create_mongodb_index(the_data_client, the_data_db, the_data_cl, index_name, unique=False):
data_client = MongoClient(the_data_client)
data_db = data_client.get_database(the_data_db)
data_col = data_db.get_collection(the_data_cl)
print "start, the index is:", index_name
data_col.ensure_index([(index_name, 1)], unique=unique)
print "run over"
if __name__ == '__main__':
DataClient = ''
DataDB = ''
DataCol = ''
IndexName = ''
create_mongodb_index(DataClient, DataDB, DataCol, index_name=IndexName, unique=False)
2、若目标集合已经存在指定名称的索引
使用create_index或则ensure_index创建与之前“唯一性unique”不同的同名索引,会出现“OperationFailure”错误。
解决方法:
首先,判断有无同名索引;然后判断同名索引是否为唯一索引;
若有同名索引,且非唯一索引,则删除已有的同名索引,然后重新建立索引。
# -*- coding:utf-8 -*-
from pymongo import MongoClient
def create_unique_index():
"""
创建唯一索引
:return:
"""
the_col = MongoClient('localhost').get_database('test_db').get_collection('test_col_1')
all_index = the_col.index_information()
print all_index # 打印所有索引信息
has_id_index = all_index.get("id_1", False) # 判断有无“id”索引
if has_id_index:
if all_index['id_1'].get('unique', False): # id为唯一索引
pass
else:
the_col.drop_index([("id", 1)])
the_col.create_index([("id", 1)], unique=True) # 尝试创建唯一索引
else:
the_col.create_index([("id", 1)], unique=True) # 尝试创建唯一索引
if __name__ == "__main__":
create_unique_index()