Python程序创建MongoDB数据库集合的唯一索引

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()

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值