mongo创建索引,查看索引,删除索引

def link_database():
       url = f'mongodb://username:password@host:port/database'
       client = motor.motor_asyncio.AsyncIOMotorClient(url)
       return client,client[database][collection]
    async def create_index(self, data, collection=None, database="finance", **kwargs):
创建索引
        client, db = self.link_database(collection, database)
        try:
            if isinstance(data, tuple):
                d = await db.create_index([], background=True)
                return d
        except Exception as e:
            print(e)
            return []
        finally:
            await self.close(client)

    async def create_indexs(self, data, collection=None, database="finance", **kwargs):
批量创建索引
        client, db = self.link_database(collection, database)
        try:
            if isinstance(data, list):
                d = await db.create_index(data, background=True)
                return d
        except Exception as e:
            print(e)
            return []
        finally:
            await self.close(client)

    async def create_unique_index(self, data, collection=None, database="finance", **kwargs):
创建唯一索引
        client, db = self.link_database(collection, database)
        try:
            if isinstance(data, tuple):
                e = await db.create_index([data], unique=True, background=True)
                return e
        except Exception:
            return []
        finally:
            await self.close(client)

    async def index_information(self, collection, database):
    查看索引
        client, db = self.link_database(collection, database)
        try:
            e = await db.index_information()
            return e
        except Exception:
            return []
        finally:
            await self.close(client)

    async def drop_indexs(self, collection, database):
    删除索引
        client, db =self.link_database(collection, database)
        try:
            await db.drop_indexes()
            return 1
        except Exception:
            return 0
        finally:
            await self.close(client)

猜你喜欢

转载自blog.csdn.net/weixin_43883907/article/details/86231089