当前位置:首页 > 日记本 > 正文内容

python 多线程 mongodb数据库:motor代码示例

zhangchap2年前 (2022-04-10)日记本414
# -*- coding: utf-8 -*-
from motor import motor_asyncio
import asyncio
import platform

if "Windows" in platform.platform():
    policy = asyncio.WindowsSelectorEventLoopPolicy()
    asyncio.set_event_loop_policy(policy)


async def init():
        client = motor_asyncio.AsyncIOMotorClient()
    # client = motor_asyncio.AsyncIOMotorClient('mongodb://127.0.0.1:27017')

    # 创建或连接数据库
    db = client['kanchai']

    # 创建或连接集合(表)
    colllection = db['article']
    return colllection


async def find_one(collection, title):
    result = await collection.find_one({"title": title}, {"_id": 0})
    print(result)

async def find_all(collection, skip, limit):
    # cousor = collection.find({}, skip=skip, limit=limit)
    # for item in await cousor.to_list(length=limit):
    #     print(item)

    async for item in collection.find({}, {"_id": 0}, skip=skip, limit=limit):
        print(item)

async def count_all(collection):
    counts = await collection.count_documents({})
    print(counts)

async def update_document(collection, title):
    ret = await collection.update_one({"title": title}, {"$set": {"isindex": 1}})
    print(ret.modified_count)

async def delete_document(collection, title):
    # ret = await collection.delete_one({"title": title})
    ret = await collection.delete_many({"title": title})
    print(f"成功删除:{ret.deleted_count}个文档")
    print(ret.acknowledged)
    print(ret.raw_result)


async def main():
    collection = await init()
    title = "全链路数字化转型下,零售企业如何做到消费者“心智占领”"
    await find_one(collection, title)
    # await find_all(collection, 9, 10)
    # await count_all(collection)
    # await update_document(collection, title)
    await delete_document(collection, title)



asyncio.run(main())


分享给朋友:

相关文章

Windows管理规范(WMI)在IIS 7

适用于:Windows 7,Windows Server 2008,Windows Server 2008 R2,Windows Vista IIS 7使用Windows管理规范(W...

python补全网址代码示例

from urllib.parse import urljoin absurl = urljoin(backend,url) #backend:根...

python xpath语法总结

python xpath语法总结:常用的://1.从任意节点开始/2.从根节点开始//div/p3.div下的p标签//div[@class="hrzz_bottom"]/ul/l...

python url.parse模块编码解码

from urllib.parse import quote,unquote,urlencode # 对汉字进行编码使用 quote ...

python读取txt文件放到Queue队列

from queue import Queue with open('kw.txt',encoding='utf-8')&nb...

Python 正则表达式 带分组的替换 \g

import re re.sub(r'([^a-z]*)[a-z]([^a-z]*)', '\g<1>\g<2>',wor...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。