当前位置: 首页 > 工具软件 > Asyncio Mongo > 使用案例 >

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

魏兴邦
2023-12-01
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)
 类似资料: